import React, { useCallback, useEffect, useMemo, useState } from 'react';
import {
  Activity,
  AlertCircle,
  AlertTriangle,
  Boxes,
  Calculator,
  Check,
  CheckCircle2,
  ClipboardCheck,
  Copy,
  Download,
  FileCode2,
  FlaskConical,
  Globe,
  Lock,
  Play,
  Plus,
  RefreshCw,
  Save,
  Send,
  ShieldAlert,
  ShieldCheck,
  Sparkles,
  Trash2,
} from 'lucide-react';
import { toast } from 'sonner';
import { useArtisan } from '../context/ArtisanContext';
import { cn } from '../lib/utils';
import type {
  AgreedCatalogSku,
  StorefrontAgreementCatalog,
  StorefrontAvailabilityStatus,
  StorefrontSkuKind,
  StorefrontTrack,
} from '../lib/storefrontBridge';
import {
  clearStagingSandbox,
  fetchStorefrontOperations,
  fetchStorefrontStatus,
  pushCatalogToStorefront,
  runIncomingOrderIntake,
  saveAgreedCatalog,
  simulateStagingEvent,
  type StorefrontOperationsResponse,
  type StorefrontStatusResponse,
  testStorefrontConnection,
  updateOutboundQueueStatus,
} from '../services/storefrontClient';

const SHARED_APP_FALLBACK_URL =
  'https://ais-pre-ifdm6lmney5cu6xd3ojm3x-359488534598.us-west2.run.app';

const STATUS_LABELS: Record<StorefrontAvailabilityStatus, string> = {
  preorder: 'Pre-Order Only',
  sample_only: 'Sample Request',
  in_development: 'In Development / Waitlist',
  in_stock: 'In Stock (Ready)',
  sold_out: 'Sold Out',
};

export const StorefrontConnector: React.FC = () => {
  const { user, businessState, refreshOperationsQueue } = useArtisan();

  const [subTab, setSubTab] = useState<
    'security' | 'inbox' | 'dossiers' | 'tables' | 'agreement' | 'handoff'
  >('security');
  const [status, setStatus] = useState<StorefrontStatusResponse | null>(null);
  const [opsData, setOpsData] = useState<StorefrontOperationsResponse | null>(null);
  const [runningIntakeId, setRunningIntakeId] = useState<string | null>(null);
  const [updatingOutboundId, setUpdatingOutboundId] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [errorMsg, setErrorMsg] = useState<string | null>(null);

  const [targetUrlInput, setTargetUrlInput] = useState('https://staging.ljwellness.net');
  const [healthTestResult, setHealthTestResult] = useState<{
    ok: boolean;
    message: string;
    environment?: string;
    checkedAt: string;
  } | null>(null);
  const [isTesting, setIsTesting] = useState(false);
  const [isSimulating, setIsSimulating] = useState(false);
  const [isPushingCatalog, setIsPushingCatalog] = useState(false);
  const [isSavingCatalog, setIsSavingCatalog] = useState(false);

  const [inboxEnv, setInboxEnv] = useState<'staging' | 'production'>('staging');
  const [catalogTrackFilter, setCatalogTrackFilter] = useState<'all' | StorefrontTrack>('all');
  const [editableCatalog, setEditableCatalog] = useState<StorefrontAgreementCatalog | null>(null);
  const [catalogDirty, setCatalogDirty] = useState(false);

  // Add Multi-Product SKU quick row
  const [newSkuForm, setNewSkuForm] = useState<{
    sku: string;
    storefrontSlug: string;
    variantKey: string;
    track: StorefrontTrack;
    kind: StorefrontSkuKind;
    nameEn: string;
    nameFr: string;
    formatLabel: string;
    priceCad: number;
    cureLeadDays: number;
  }>({
    sku: '',
    storefrontSlug: '',
    variantKey: 'default',
    track: 'menopause',
    kind: 'product',
    nameEn: '',
    nameFr: '',
    formatLabel: '',
    priceCad: 0,
    cureLeadDays: 14,
  });

  const [copiedKey, setCopiedKey] = useState<string | null>(null);

  const loadStatus = useCallback(async () => {
    if (!user) {
      setStatus(null);
      setOpsData(null);
      return;
    }
    setLoading(true);
    setErrorMsg(null);
    try {
      const [data, ops] = await Promise.all([
        fetchStorefrontStatus(),
        fetchStorefrontOperations().catch(() => null),
      ]);
      setStatus(data);
      if (ops) setOpsData(ops);
      setTargetUrlInput((prev) =>
        prev === 'https://staging.ljwellness.net' && data.storefrontUrl ? data.storefrontUrl : prev,
      );
      setEditableCatalog(data.catalog);
      setCatalogDirty(false);
    } catch (err: any) {
      setErrorMsg(err?.message || 'Unable to load Storefront connector status.');
    } finally {
      setLoading(false);
    }
  }, [user]);

  useEffect(() => {
    loadStatus();
  }, [loadStatus]);

  const ourBaseUrl = status?.ourSharedBaseUrl || SHARED_APP_FALLBACK_URL;

  const handleCopy = (key: string, text: string) => {
    navigator.clipboard?.writeText(text);
    setCopiedKey(key);
    toast.success('Copied to clipboard');
    setTimeout(() => setCopiedKey(null), 2000);
  };

  const handleTestConnection = async () => {
    setIsTesting(true);
    try {
      const result = await testStorefrontConnection(targetUrlInput);
      setHealthTestResult({
        ok: result.ok,
        environment: result.environment,
        message: result.ok
          ? `Connected cleanly (HTTP ${result.httpStatus}) -> ${result.targetUrl}`
          : `HTTP ${result.httpStatus} at ${result.targetUrl}`,
        checkedAt: new Date().toLocaleTimeString(),
      });
      toast.success(`Storefront health responded (HTTP ${result.httpStatus})`);
    } catch (err: any) {
      setHealthTestResult({
        ok: false,
        message: err?.message || 'Storefront unreachable — check cPanel Express server & STOREFRONT_URL.',
        checkedAt: new Date().toLocaleTimeString(),
      });
      toast.error(err?.message || 'Storefront health check failed.');
    } finally {
      setIsTesting(false);
    }
  };

  const handleSimulateStaging = async (track: 'b2b' | 'eczema' | 'menopause') => {
    setIsSimulating(true);
    try {
      const res = await simulateStagingEvent(track);
      toast.success(
        `Staging test (${track.toUpperCase()}) isolated to sandbox — Live CRM untouched: ${res.crmLeadCreated ? 'NO' : 'Verified Isolated'}`,
      );
      setInboxEnv('staging');
      await loadStatus();
    } catch (err: any) {
      toast.error(err?.message || 'Staging test failed.');
    } finally {
      setIsSimulating(false);
    }
  };

  const handleClearStaging = async () => {
    try {
      await clearStagingSandbox();
      toast.success('Staging sandbox cleared.');
      await loadStatus();
    } catch (err: any) {
      toast.error(err?.message || 'Failed to clear staging sandbox.');
    }
  };

  const handleRunIntake = async (incomingId: string) => {
    setRunningIntakeId(incomingId);
    try {
      const res = await runIncomingOrderIntake(incomingId);
      toast.success(`Arty Dossier updated for ${res.order.referenceCode} (Internal only — zero external sends).`);
      await Promise.all([loadStatus(), refreshOperationsQueue()]);
    } catch (err: any) {
      toast.error(err?.message || 'Unable to execute Arty intake review.');
    } finally {
      setRunningIntakeId(null);
    }
  };

  const handleOutboundStatus = async (
    outboundId: string,
    nextStatus: 'ready_for_review' | 'approved_copied' | 'resolved',
  ) => {
    setUpdatingOutboundId(outboundId);
    try {
      await updateOutboundQueueStatus(outboundId, nextStatus);
      toast.success(`Internal review item marked ${nextStatus.replace(/_/g, ' ')}.`);
      await Promise.all([loadStatus(), refreshOperationsQueue()]);
    } catch (err: any) {
      toast.error(err?.message || 'Failed to update internal queue status.');
    } finally {
      setUpdatingOutboundId(null);
    }
  };

  const updateSkuField = <K extends keyof AgreedCatalogSku>(
    sku: string,
    field: K,
    value: AgreedCatalogSku[K],
  ) => {
    if (!editableCatalog) return;
    setEditableCatalog({
      ...editableCatalog,
      products: editableCatalog.products.map((p) => (p.sku === sku ? { ...p, [field]: value } : p)),
    });
    setCatalogDirty(true);
  };

  const handleAddSku = (e: React.FormEvent) => {
    e.preventDefault();
    if (!editableCatalog) return;

    const cleanSku = newSkuForm.sku.trim().toUpperCase().replace(/[^A-Z0-9_-]/g, '-');
    const cleanSlug = newSkuForm.storefrontSlug.trim().toLowerCase().replace(/[^a-z0-9_-]/g, '-');
    if (!cleanSku || cleanSku.length < 3 || !cleanSlug || !newSkuForm.nameEn.trim()) {
      toast.error('Please enter a SKU (e.g. LJW-MEN-SERUM-30), storefront slug, and English product name.');
      return;
    }
    if (editableCatalog.products.some((p) => p.sku === cleanSku)) {
      toast.error(`SKU ${cleanSku} already exists in the agreement table.`);
      return;
    }

    const created: AgreedCatalogSku = {
      sku: cleanSku,
      storefrontSlug: cleanSlug,
      variantKey: newSkuForm.variantKey.trim() || 'default',
      track: newSkuForm.track,
      kind: newSkuForm.kind,
      nameEn: newSkuForm.nameEn.trim(),
      nameFr: newSkuForm.nameFr.trim() || newSkuForm.nameEn.trim(),
      formatLabel: newSkuForm.formatLabel.trim() || 'Studio Formulation',
      priceCad: Math.max(0, Number(newSkuForm.priceCad) || 0),
      status: 'in_development',
      stockAvailable: 0,
      cureLeadDays: Math.max(0, Number(newSkuForm.cureLeadDays) || 14),
      cureReadyDate: null,
      moq: newSkuForm.track === 'b2b' ? 5 : 1,
      unitCogsCad: 0,
      deductsMaterials: true,
      activeOnStorefront: true,
    };

    setEditableCatalog({
      ...editableCatalog,
      products: [created, ...editableCatalog.products],
    });
    setCatalogDirty(true);
    setNewSkuForm({
      sku: '',
      storefrontSlug: '',
      variantKey: 'default',
      track: newSkuForm.track,
      kind: 'product',
      nameEn: '',
      nameFr: '',
      formatLabel: '',
      priceCad: 0,
      cureLeadDays: 14,
    });
    toast.success(`Added ${cleanSku} (${created.track.toUpperCase()}). Remember to Save Agreement.`);
  };

  const handleRemoveSku = (sku: string) => {
    if (!editableCatalog) return;
    setEditableCatalog({
      ...editableCatalog,
      products: editableCatalog.products.filter((p) => p.sku !== sku),
    });
    setCatalogDirty(true);
  };

  const handleSaveCatalog = async () => {
    if (!editableCatalog) return;
    setIsSavingCatalog(true);
    try {
      const res = await saveAgreedCatalog(editableCatalog);
      setEditableCatalog(res.catalog);
      setCatalogDirty(false);
      toast.success(`Saved Canonical Agreement v${res.catalog.catalogVersion} (${res.catalog.products.length} SKUs)`);
      await loadStatus();
    } catch (err: any) {
      toast.error(err?.message || 'Failed to save catalog agreement.');
    } finally {
      setIsSavingCatalog(false);
    }
  };

  const handlePushCatalog = async () => {
    setIsPushingCatalog(true);
    try {
      if (catalogDirty && editableCatalog) {
        await saveAgreedCatalog(editableCatalog);
        setCatalogDirty(false);
      }
      const res = await pushCatalogToStorefront(targetUrlInput);
      toast.success(
        `Pushed Catalog v${res.catalogVersion} (${res.skuCount} SKUs) to Storefront (HTTP ${res.httpStatus})`,
      );
    } catch (err: any) {
      toast.error(
        err?.message || 'Storefront catalog push failed. Make sure /api/studio/catalog-sync is deployed on cPanel.',
      );
    } finally {
      setIsPushingCatalog(false);
    }
  };

  const filteredProducts = useMemo(() => {
    if (!editableCatalog) return [];
    if (catalogTrackFilter === 'all') return editableCatalog.products;
    return editableCatalog.products.filter((p) => p.track === catalogTrackFilter);
  }, [editableCatalog, catalogTrackFilter]);

  const trackCounts = useMemo(() => {
    const prods = editableCatalog?.products || [];
    return {
      all: prods.length,
      b2b: prods.filter((p) => p.track === 'b2b').length,
      eczema: prods.filter((p) => p.track === 'eczema').length,
      menopause: prods.filter((p) => p.track === 'menopause').length,
      purity: prods.filter((p) => p.track === 'purity').length,
    };
  }, [editableCatalog]);

  const activeEvents =
    inboxEnv === 'staging' ? status?.stagingEvents || [] : status?.productionEvents || [];

  const mergedIncomingOrders = useMemo(() => {
    const map = new Map<string, NonNullable<typeof businessState.incomingOrders>[number]>();
    for (const o of businessState.incomingOrders || []) map.set(o.id, o);
    for (const o of opsData?.incomingOrders || []) map.set(o.id, o);
    return Array.from(map.values()).sort((a, b) => (b.receivedAt || '').localeCompare(a.receivedAt || ''));
  }, [businessState.incomingOrders, opsData?.incomingOrders]);

  const mergedOutboundQueue = useMemo(() => {
    const map = new Map<string, NonNullable<typeof businessState.outboundQueue>[number]>();
    for (const q of businessState.outboundQueue || []) map.set(q.id, q);
    for (const q of opsData?.outboundQueue || []) map.set(q.id, q);
    return Array.from(map.values()).sort((a, b) => (b.createdAt || '').localeCompare(a.createdAt || ''));
  }, [businessState.outboundQueue, opsData?.outboundQueue]);

  const storefrontHandoffMarkdown = useMemo(() => {
    return `# LJWellness Storefront (\`ljwellness-vs3\`) -> Artisan 2nd Brain Integration Spec (\`ljw-storefront-v1\`)

Implement this server-to-server bridge inside \`ljwellness-vs3\`'s Express server (\`server.ts\` -> \`server.bundle.mjs\` on Namecheap cPanel) so all B2B inquiries, Eczema orders/reservations, and Menopause requests sync securely to Artisan 2nd Brain.

## 1. Strict Security Rules (Non-Negotiable)
1. **Zero secrets in browser/React code**: NEVER put \`STUDIOOS_BRIDGE_KEY\` or \`STUDIOOS_HMAC_SECRET\` in \`src/\` or \`VITE_*\`.
2. **Server-side relay only**: Add a same-origin Express route \`POST /api/sync/studio\` on Storefront \`server.ts\`. Browser forms submit to Firestore + call \`POST /api/sync/studio\` (or server writes + relays).
3. **HMAC-SHA256 + 5-Min Replay Guard**: Every server-to-server request to Artisan 2nd Brain signs \`<unixTimestampSeconds>.<rawJsonBody>\`:
   - \`X-Bridge-Key: <STUDIOOS_BRIDGE_KEY>\`
   - \`X-Bridge-Timestamp: <unixSeconds>\`
   - \`X-Bridge-Signature: sha256=<hmac_sha256_hex>\`
4. **Explicit Staging vs. Production Environment Flag**:
   - Storefront's existing \`stagingMode\` (\`'bulk_studio' | 'direct_homeowner'\`) is delivery preference, NOT environment!
   - Always send \`environment: process.env.LJWELLNESS_ENV === 'production' ? 'production' : 'staging'\` (also inferable on server from \`req.hostname.startsWith('staging.')\`).
   - \`environment: "staging"\` payloads go strictly to Artisan 2nd Brain's isolated \`storefront_staging_events\` sandbox and NEVER touch live CRM, inventory, or ledgers.
5. **No Unverified Paid Claims & PII Health Minimization**:
   - NEVER send \`eventType: "retail_paid_order"\` until Stripe server webhook verification is live (\`paymentVerification.verifiedOnStorefrontServer === true\`).
   - Until then, send \`b2b_inquiry\`, \`b2b_sample_request\`, or \`retail_preorder\`.

## 2. Namecheap cPanel Node.js Environment Variables
Configure these in cPanel -> Setup Node.js App -> Environment Variables (never commit secrets):
- \`LJWELLNESS_ENV\` = \`staging\` on \`staging.ljwellness.net\` (change to \`production\` on \`ljwellness.net\`)
- \`STUDIOOS_URL\` = \`${ourBaseUrl}\`
- \`STUDIOOS_BRIDGE_KEY\` = *(same value as \`STOREFRONT_BRIDGE_KEY\` in Artisan 2nd Brain Secrets)*
- \`STUDIOOS_HMAC_SECRET\` = *(same value as \`STOREFRONT_HMAC_SECRET\` in Artisan 2nd Brain Secrets)*

## 3. Artisan 2nd Brain Endpoints Exposed for Storefront
- **Health**: \`GET ${ourBaseUrl}/api/storefront/health\`
- **Inbound Event Sync**: \`POST ${ourBaseUrl}/api/storefront/inbound\`
- **Pull Canonical Agreed Catalog**: \`GET ${ourBaseUrl}/api/storefront/catalog\` *(requires \`X-Bridge-Key\` + \`X-Bridge-Timestamp\` + \`X-Bridge-Signature\` over \`<ts>.\`)*

## 4. Required Routes to Add in \`ljwellness-vs3\` \`server.ts\`
1. \`POST /api/sync/studio\` — Accepts form submission summary from Storefront UI, enforces strict server schema + rate limit, stamps \`environment\` (\`'staging' | 'production'\`), \`idempotencyKey\`, \`track\` (\`'b2b' | 'eczema' | 'menopause'\`), \`lineItems[]\`, signs payload with HMAC-SHA256 + timestamp, and POSTs to \`\${STUDIOOS_URL}/api/storefront/inbound\`.
2. \`POST /api/studio/catalog-sync\` — Verifies Artisan 2nd Brain \`X-Bridge-Key\` + timestamped HMAC signature, allow-lists synced fields (\`sku\`, \`storefrontSlug\`, \`variantKey\`, \`priceCad\`, \`status\`, \`stockAvailable\`, \`cureLeadDays\`, \`cureReadyDate\`, \`moq\`, \`nameEn\`, \`nameFr\`, \`activeOnStorefront\`) into Firestore \`storeProducts\` without overwriting Storefront images or long marketing copy.
3. Add CORS only if needed, and keep \`express.json({ verify: (req, _res, buf) => { req.rawBody = buf; } })\` so raw-body HMAC verification is exact.

## 5. Brand & Multi-Product Catalog Agreement
- **Primary Brand Face**: \`b2b\` (Luxury Builders, Architects, Developers, Realtors: \`residence-welcome\`, \`architectural-sanctuary\`, \`bespoke-estate\`, \`studio-material-sample-box\`, and 5 co-branding add-ons).
- **Multi-Product Skincare Tracks**: Storefront supports multiple SKUs under \`eczema\` (\`oat-borage-barrier-balm\`, \`amino-lipid-gentle-wash\`, \`pocket-crease-flare-stick\`, bundles, waitlists) and \`menopause\` (existing 6 concepts + incoming *Say It Plain* SKUs).
- **Launch Truth**: Until real manufacturing & Stripe go live, Storefront reads \`status\` (\`preorder\`, \`sample_only\`, \`in_development\`, \`in_stock\`, \`sold_out\`) from Artisan 2nd Brain's Canonical Catalog Agreement rather than hardcoding "Available Now".`;
  }, [ourBaseUrl]);

  return (
    <div className="space-y-8">
      {/* Top Status & Target Storefront Controls */}
      <div className="neu-flat rounded-[3rem] p-8 border border-gold/20 bg-paper/70 space-y-6">
        <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-6">
          <div className="space-y-2 max-w-2xl">
            <div className="flex flex-wrap items-center gap-2 text-[10px] font-black uppercase tracking-widest text-gold">
              <Globe size={13} />
              <span>Storefront Integration · Protocol ljw-storefront-v1</span>
              <span className="px-2 py-0.5 rounded-md bg-ink/5 text-ink/70">
                B2B Flagship + Multi-Product Skincare
              </span>
            </div>
            <h2 className="text-2xl md:text-3xl font-black text-ink tracking-tight">
              LJWellness Storefront Connector &amp; Catalog Agreement
            </h2>
            <p className="text-xs font-medium text-ink/60 leading-relaxed">
              Connects your Namecheap cPanel Storefront (<code className="font-mono text-ink">staging.ljwellness.net</code> / <code className="font-mono text-ink">ljwellness.net</code>) to Artisan 2nd Brain via HMAC-SHA256 + 5-minute replay guard, strict Staging Sandbox isolation, and a single agreed SKU truth table.
            </p>
          </div>

          <div className="flex flex-wrap items-center gap-3 shrink-0">
            <button
              type="button"
              onClick={loadStatus}
              disabled={loading}
              className="px-4 py-2.5 neu-button rounded-xl text-[10px] font-black uppercase tracking-wider text-ink/70 hover:text-gold flex items-center gap-2"
            >
              <RefreshCw size={13} className={loading ? 'animate-spin' : ''} />
              <span>Refresh</span>
            </button>
            <button
              type="button"
              onClick={handleTestConnection}
              disabled={isTesting}
              className="px-5 py-2.5 bg-gold text-ink rounded-xl text-[10px] font-black uppercase tracking-wider hover:bg-bronze hover:text-paper transition-colors flex items-center gap-2 shadow-sm"
            >
              <Activity size={13} />
              <span>{isTesting ? 'Pinging...' : 'Test Storefront Health'}</span>
            </button>
          </div>
        </div>

        {/* Storefront URL Input & Server Health Result */}
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-4 items-center pt-2 border-t border-ink/5">
          <div className="lg:col-span-6 space-y-1.5">
            <label className="text-[10px] font-black uppercase tracking-widest text-ink/50 block">
              Target Storefront Origin (Staging or Production)
            </label>
            <div className="flex gap-2">
              <input
                type="url"
                value={targetUrlInput}
                onChange={(e) => setTargetUrlInput(e.target.value)}
                placeholder="https://staging.ljwellness.net"
                className="flex-1 px-4 py-2.5 rounded-xl bg-paper border border-ink/10 text-xs font-mono text-ink focus:outline-none focus:border-gold"
              />
              <button
                type="button"
                onClick={() => setTargetUrlInput('https://staging.ljwellness.net')}
                className="px-3 py-2 rounded-xl neu-button text-[10px] font-bold text-ink/70 hover:text-gold whitespace-nowrap"
              >
                Staging
              </button>
              <button
                type="button"
                onClick={() => setTargetUrlInput('https://ljwellness.net')}
                className="px-3 py-2 rounded-xl neu-button text-[10px] font-bold text-ink/70 hover:text-gold whitespace-nowrap"
              >
                Production
              </button>
            </div>
          </div>

          <div className="lg:col-span-6 flex flex-wrap gap-3 items-center lg:justify-end">
            <div className="px-3.5 py-2 rounded-xl neu-pressed text-[11px] font-bold flex items-center gap-2">
              {status?.keyConfigured ? (
                <CheckCircle2 size={14} className="text-emerald-700" />
              ) : (
                <AlertCircle size={14} className="text-amber-600" />
              )}
              <span>
                Key: {status?.keyConfigured ? 'Configured in Env' : 'Missing STOREFRONT_BRIDGE_KEY'}
              </span>
            </div>
            <div className="px-3.5 py-2 rounded-xl neu-pressed text-[11px] font-bold flex items-center gap-2">
              {status?.hmacConfigured ? (
                <ShieldCheck size={14} className="text-emerald-700" />
              ) : (
                <AlertCircle size={14} className="text-amber-600" />
              )}
              <span>
                HMAC + 5m Replay: {status?.hmacConfigured ? 'Active' : 'Set STOREFRONT_HMAC_SECRET'}
              </span>
            </div>
          </div>
        </div>

        {healthTestResult && (
          <div
            className={cn(
              'rounded-2xl p-4 text-xs font-semibold flex items-center justify-between gap-3 border',
              healthTestResult.ok
                ? 'bg-emerald-500/10 border-emerald-500/30 text-emerald-900'
                : 'bg-amber-500/10 border-amber-500/30 text-amber-950',
            )}
          >
            <div className="flex items-center gap-2">
              {healthTestResult.ok ? <CheckCircle2 size={15} /> : <AlertCircle size={15} />}
              <span>{healthTestResult.message}</span>
            </div>
            <span className="text-[10px] opacity-70">{healthTestResult.checkedAt}</span>
          </div>
        )}

        {errorMsg && (
          <div className="rounded-2xl p-4 bg-rose-500/10 border border-rose-500/30 text-rose-900 text-xs font-semibold">
            {errorMsg}
          </div>
        )}
      </div>

      {/* Sub-navigation Tabs */}
      <div className="flex flex-wrap gap-2.5">
        {[
          { id: 'security', label: '1. Connection & Security', icon: <Lock size={14} /> },
          {
            id: 'inbox',
            label: `2. Staging & Production Inbox (${(status?.stagingEvents.length || 0) + (status?.productionEvents.length || 0)})`,
            icon: <FlaskConical size={14} />,
          },
          {
            id: 'dossiers',
            label: `3. Arty Dossiers & Queue (${mergedIncomingOrders.length})`,
            icon: <ClipboardCheck size={14} />,
          },
          {
            id: 'tables',
            label: `4. Studio BOM, Stock & COGS Tables`,
            icon: <Calculator size={14} />,
          },
          {
            id: 'agreement',
            label: `5. SKU Agreement (${editableCatalog?.products.length || 0})`,
            icon: <Sparkles size={14} />,
          },
          { id: 'handoff', label: '6. Storefront Spec (.md)', icon: <FileCode2 size={14} /> },
        ].map((tab) => (
          <button
            key={tab.id}
            type="button"
            onClick={() => setSubTab(tab.id as any)}
            className={cn(
              'px-4 py-2.5 rounded-2xl text-[11px] font-black uppercase tracking-wider flex items-center gap-2 transition-all',
              subTab === tab.id
                ? 'bg-gold text-ink shadow-md'
                : 'neu-button text-ink/70 hover:text-gold',
            )}
          >
            {tab.icon}
            <span>{tab.label}</span>
          </button>
        ))}
      </div>

      {/* TAB 1: CONNECTION & SECURITY */}
      {subTab === 'security' && (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          <div className="neu-flat rounded-[2.5rem] p-8 space-y-5 border border-white/50">
            <h3 className="text-lg font-black text-ink">StudioOS Endpoints for Namecheap cPanel</h3>
            <p className="text-xs text-ink/60 leading-relaxed">
              Your Storefront server (<code className="font-mono text-ink">ljwellness-vs3</code>) pushes events and pulls the agreed SKU truth table using these server-only endpoints:
            </p>

            {[
              { label: 'Inbound Webhook (B2B / Pre-Orders / Orders)', url: `${ourBaseUrl}/api/storefront/inbound` },
              { label: 'Canonical Catalog Pull (Agreed B2B + Skincare SKUs)', url: `${ourBaseUrl}/api/storefront/catalog` },
              { label: 'Public Health Check', url: `${ourBaseUrl}/api/storefront/health` },
            ].map((ep) => (
              <div key={ep.label} className="p-4 rounded-2xl neu-pressed space-y-1.5">
                <div className="text-[10px] font-black uppercase tracking-wider text-ink/50">
                  {ep.label}
                </div>
                <div className="flex items-center justify-between gap-2">
                  <code className="text-xs font-mono text-ink break-all">{ep.url}</code>
                  <button
                    type="button"
                    onClick={() => handleCopy(ep.label, ep.url)}
                    className="p-2 rounded-lg neu-button text-ink/70 hover:text-gold shrink-0"
                    title="Copy URL"
                  >
                    {copiedKey === ep.label ? <Check size={13} /> : <Copy size={13} />}
                  </button>
                </div>
              </div>
            ))}
          </div>

          <div className="neu-flat rounded-[2.5rem] p-8 space-y-5 border border-white/50">
            <h3 className="text-lg font-black text-ink">Zero-Trust Security &amp; Safeguards Active</h3>
            <ul className="space-y-3 text-xs text-ink/75 leading-relaxed">
              <li className="p-3.5 rounded-2xl bg-paper/70 border border-ink/5">
                <strong className="text-ink block">1. Server-to-Server Auth + 5-Min Replay Window</strong>
                Requires <code className="font-mono">X-Bridge-Key</code> plus <code className="font-mono">X-Bridge-Timestamp</code> and <code className="font-mono">X-Bridge-Signature</code> (HMAC-SHA256 over <code className="font-mono">{`<ts>.<rawBody>`}</code>). Replays older than 300s are automatically rejected.
              </li>
              <li className="p-3.5 rounded-2xl bg-paper/70 border border-ink/5">
                <strong className="text-ink block">2. Strict Staging vs. Production Isolation</strong>
                Storefront <code className="font-mono">stagingMode</code> (<code className="font-mono">bulk_studio</code> vs <code className="font-mono">direct_homeowner</code>) is never mistaken for environment. Payloads tagged <code className="font-mono">environment: "staging"</code> are locked inside <code className="font-mono">storefront_staging_events</code> and NEVER create CRM leads, tasks, or inventory deductions.
              </li>
              <li className="p-3.5 rounded-2xl bg-paper/70 border border-ink/5">
                <strong className="text-ink block">3. PII &amp; Health Notes Minimization</strong>
                Free-text skin/symptom narratives (<code className="font-mono">skinOrRitualFocus</code>) on Eczema &amp; Menopause tracks are redacted at intake, preserving only structured SKUs, quantities, and totals.
              </li>
              <li className="p-3.5 rounded-2xl bg-paper/70 border border-ink/5">
                <strong className="text-ink block">4. Fake Payment &amp; SSRF Prevention</strong>
                Paid-order sync is blocked unless Storefront provides server-verified Stripe intent data, and outbound URLs block private/metadata IP ranges.
              </li>
            </ul>
          </div>
        </div>
      )}

      {/* TAB 2: STAGING & PRODUCTION INBOX */}
      {subTab === 'inbox' && (
        <div className="neu-flat rounded-[2.5rem] p-8 space-y-6 border border-white/50">
          <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
            <div className="flex items-center gap-2">
              <button
                type="button"
                onClick={() => setInboxEnv('staging')}
                className={cn(
                  'px-4 py-2 rounded-xl text-[11px] font-black uppercase tracking-wider',
                  inboxEnv === 'staging'
                    ? 'bg-amber-500/20 text-amber-950 border border-amber-500/40'
                    : 'neu-button text-ink/60',
                )}
              >
                Staging Sandbox ({status?.stagingEvents.length || 0})
              </button>
              <button
                type="button"
                onClick={() => setInboxEnv('production')}
                className={cn(
                  'px-4 py-2 rounded-xl text-[11px] font-black uppercase tracking-wider',
                  inboxEnv === 'production'
                    ? 'bg-emerald-500/20 text-emerald-950 border border-emerald-500/40'
                    : 'neu-button text-ink/60',
                )}
              >
                Live Production ({status?.productionEvents.length || 0})
              </button>
            </div>

            <div className="flex flex-wrap items-center gap-2">
              <button
                type="button"
                disabled={isSimulating}
                onClick={() => handleSimulateStaging('b2b')}
                className="px-3.5 py-2 rounded-xl neu-button text-[10px] font-black uppercase tracking-wider text-ink hover:text-gold"
              >
                Simulate Staging B2B
              </button>
              <button
                type="button"
                disabled={isSimulating}
                onClick={() => handleSimulateStaging('eczema')}
                className="px-3.5 py-2 rounded-xl neu-button text-[10px] font-black uppercase tracking-wider text-ink hover:text-gold"
              >
                Simulate Staging Eczema
              </button>
              <button
                type="button"
                disabled={isSimulating}
                onClick={() => handleSimulateStaging('menopause')}
                className="px-3.5 py-2 rounded-xl neu-button text-[10px] font-black uppercase tracking-wider text-ink hover:text-gold"
              >
                Simulate Staging Menopause
              </button>
              {inboxEnv === 'staging' && (status?.stagingEvents.length || 0) > 0 && (
                <button
                  type="button"
                  onClick={handleClearStaging}
                  className="px-3.5 py-2 rounded-xl bg-rose-500/10 text-rose-800 border border-rose-500/20 text-[10px] font-black uppercase tracking-wider flex items-center gap-1"
                >
                  <Trash2 size={12} />
                  <span>Clear Sandbox</span>
                </button>
              )}
            </div>
          </div>

          {activeEvents.length === 0 ? (
            <div className="p-10 rounded-3xl neu-pressed text-center space-y-2">
              <p className="text-sm font-bold text-ink">
                No {inboxEnv === 'staging' ? 'Staging Sandbox' : 'Live Production'} events received yet.
              </p>
              <p className="text-xs text-ink/60">
                Use the <strong>Simulate Staging</strong> buttons above to verify sandbox isolation &amp; PII redaction right now, or wire the Handoff Spec onto <code className="font-mono">staging.ljwellness.net</code>.
              </p>
            </div>
          ) : (
            <div className="space-y-3">
              {activeEvents.map((ev) => (
                <div
                  key={ev.id}
                  className="p-5 rounded-2xl bg-paper/80 border border-ink/10 space-y-2.5"
                >
                  <div className="flex flex-wrap items-center justify-between gap-2">
                    <div className="flex flex-wrap items-center gap-2">
                      <span className="px-2.5 py-1 rounded-lg bg-gold/20 text-ink text-[10px] font-black uppercase">
                        {ev.track}
                      </span>
                      <span className="text-sm font-black text-ink">{ev.referenceCode}</span>
                      <span className="text-xs text-ink/60">{ev.eventType}</span>
                      {ev.isolatedToSandbox && (
                        <span className="px-2 py-0.5 rounded-md bg-amber-500/20 text-amber-950 text-[10px] font-bold">
                          Sandbox Isolated (No Live CRM Mutation)
                        </span>
                      )}
                      {ev.crmLeadCreated && (
                        <span className="px-2 py-0.5 rounded-md bg-emerald-500/20 text-emerald-950 text-[10px] font-bold">
                          B2B CRM + Task Created
                        </span>
                      )}
                      {ev.healthNotesRedacted && (
                        <span className="px-2 py-0.5 rounded-md bg-sky-500/15 text-sky-900 text-[10px] font-bold">
                          Health PII Redacted
                        </span>
                      )}
                    </div>
                    <span className="text-xs font-bold text-ink">
                      ${ev.totalCad.toFixed(2)} CAD (Est. Tax ${ev.taxBreakdown.totalTaxCad.toFixed(2)})
                    </span>
                  </div>

                  <div className="text-xs text-ink/70 flex flex-wrap gap-x-6 gap-y-1">
                    <span>
                      <strong>Contact:</strong>{' '}
                      {ev.contactSummary.firmName ? `${ev.contactSummary.firmName} — ` : ''}
                      {ev.contactSummary.contactName} ({ev.contactSummary.email})
                    </span>
                    <span>
                      <strong>Locale:</strong> {ev.locale.toUpperCase()}
                      {ev.province ? ` (${ev.province})` : ''}
                    </span>
                    {ev.fulfillmentPreference && (
                      <span>
                        <strong>Fulfillment:</strong> {ev.fulfillmentPreference}
                      </span>
                    )}
                  </div>

                  {ev.lineItems.length > 0 && (
                    <div className="text-[11px] font-mono text-ink/80 bg-ink/5 rounded-xl px-3 py-2">
                      {ev.lineItems
                        .map((li) => `${li.qty}x ${li.name} (${li.sku || li.storefrontSlug}) @ $${li.unitPriceCad}`)
                        .join(' · ')}
                    </div>
                  )}

                  {ev.sanitizedNotes && (
                    <p className="text-[11px] text-ink/60 italic">{ev.sanitizedNotes}</p>
                  )}
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {/* TAB 3: ARTY INTERNAL PRODUCTION & COSTING DOSSIERS + OUTBOUND REVIEW QUEUE */}
      {subTab === 'dossiers' && (
        <div className="space-y-6">
          {/* Strictly Internal Non-Negotiable Banner */}
          <div className="rounded-3xl border border-gold/40 bg-gold/10 p-5 flex flex-col md:flex-row md:items-center justify-between gap-4">
            <div className="flex items-start gap-3">
              <ShieldAlert size={20} className="text-bronze shrink-0 mt-0.5" />
              <div className="space-y-1">
                <h3 className="text-sm font-black uppercase tracking-wider text-ink">
                  Arty Internal Office &amp; Production Guardrails Active
                </h3>
                <p className="text-xs text-ink/75 leading-relaxed">
                  Zero external emails, SMS, webhooks, or client replies are ever sent by agents. All COGS breakdowns, 50% B2B deposit checks, and material restock lists below are prepared exclusively for Myrna&apos;s internal review before copying into Storefront <code className="font-mono">#admin</code> or approving batch deductions.
                </p>
              </div>
            </div>
            <button
              type="button"
              onClick={loadStatus}
              className="px-4 py-2 rounded-xl neu-button text-[10px] font-black uppercase tracking-wider text-ink hover:text-gold shrink-0"
            >
              Sync Dossiers
            </button>
          </div>

          {/* Incoming Orders & Quotes Dossiers */}
          <div className="neu-flat rounded-[2.5rem] p-8 space-y-5 border border-white/50">
            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
              <div>
                <h3 className="text-xl font-black text-ink">
                  Production &amp; Costing Dossiers ({mergedIncomingOrders.length})
                </h3>
                <p className="text-xs text-ink/60 mt-1">
                  Finished stock vs. production gap, raw &amp; packaging BOM shortfalls, all-track COGS &amp; margin audit, 50% B2B deposit coverage check, and safe cure/ship window.
                </p>
              </div>
            </div>

            {mergedIncomingOrders.length === 0 ? (
              <div className="p-8 rounded-3xl neu-pressed text-center space-y-2">
                <p className="text-sm font-bold text-ink">No incoming orders or quotes in the dossier queue yet.</p>
                <p className="text-xs text-ink/60">
                  Run a <strong>Simulate Staging</strong> event in Tab 2 to preview Arty&apos;s sandbox costing dossier, or trigger a live quote from Storefront.
                </p>
              </div>
            ) : (
              <div className="space-y-5">
                {mergedIncomingOrders.map((order) => {
                  const ev = order.evaluation;
                  const adminCopySummary = ev
                    ? [
                        `Reference: ${order.referenceCode} (${order.environment.toUpperCase()} / ${order.requestType})`,
                        `Client: ${order.client.companyName} — ${order.client.contactPerson} (${order.province || 'CA'})`,
                        `Dossier Status: ${(ev.dossierStatus || order.status).toUpperCase()}`,
                        `Units: ${ev.totalUnits} (Stock: ${ev.totalFinishedStockAvailable ?? 0} | To Pour: ${ev.totalUnitsToProduce ?? ev.totalUnits})`,
                        `Net Revenue: $${(ev.netRevenueCad ?? ev.quotedSubtotalCad).toFixed(2)} CAD | Est. COGS: $${ev.totalCogsCad.toFixed(2)} CAD (Direct Raw+Pkg: $${(ev.directMaterialsAndPackagingCogsCad ?? 0).toFixed(2)})`,
                        `Gross Profit: $${ev.estimatedGrossProfitCad.toFixed(2)} CAD (${ev.grossMarginPct.toFixed(1)}% margin${ev.meetsMarginFloor ? '' : ' - BELOW 70% FLOOR'})`,
                        `50% B2B Deposit Required: $${ev.b2bDepositRequiredCad.toFixed(2)} CAD (Covers Direct COGS: ${ev.b2bDepositCoversDirectCogs ? 'YES' : `NO - Gap $${(ev.depositCashFlowGapCad || 0).toFixed(2)}`})`,
                        ev.taxPreview
                          ? `Tax Preview (${ev.taxPreview.province || order.province || 'CA'}): TPS $${ev.taxPreview.tpsCad.toFixed(2)} / TVQ $${ev.taxPreview.tvqCad.toFixed(2)} / HST $${ev.taxPreview.hstCad.toFixed(2)} (Total Tax $${ev.taxPreview.totalTaxCad.toFixed(2)})`
                          : '',
                        `Earliest Safe Ship Date: ${ev.earliestPossibleDeliveryDate} (Max Cure: ${ev.maxCureTimeDays}d${ev.cureFeasible ? '' : ' - TIMELINE ADJUSTMENT REQUIRED'})`,
                        ev.hasShortfalls
                          ? `Shortfalls: ${ev.shortfalls.map((s) => `${s.itemName}: need +${s.shortfallQty} ${s.unit} ($${s.estimatedReorderCostCad.toFixed(2)}, ~${s.supplierLeadDays ?? 7}d lead)`).join('; ')}`
                          : 'Shortfalls: None',
                      ]
                        .filter(Boolean)
                        .join('\n')
                    : `${order.referenceCode} — awaiting evaluation`;

                  return (
                    <div
                      key={order.id}
                      className="p-6 rounded-3xl bg-paper/85 border border-ink/12 space-y-4"
                    >
                      <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-3 pb-3 border-b border-ink/10">
                        <div className="flex flex-wrap items-center gap-2">
                          <span className="px-2.5 py-1 rounded-lg bg-ink text-paper text-[10px] font-black uppercase">
                            {order.requestType === 'paid_order' ? 'Paid Order' : 'Quote Request'}
                          </span>
                          <span className="text-base font-black text-ink">{order.referenceCode}</span>
                          <span
                            className={cn(
                              'px-2.5 py-0.5 rounded-md text-[10px] font-bold uppercase',
                              order.environment === 'staging'
                                ? 'bg-amber-500/20 text-amber-950'
                                : 'bg-emerald-500/20 text-emerald-950',
                            )}
                          >
                            {order.environment === 'staging' ? 'Sandbox Quarantine' : 'Production'}
                          </span>
                          {ev?.dossierStatus && (
                            <span
                              className={cn(
                                'px-2.5 py-0.5 rounded-md text-[10px] font-bold uppercase',
                                ev.dossierStatus === 'approved_for_quote'
                                  ? 'bg-emerald-500/15 text-emerald-900'
                                  : ev.dossierStatus === 'needs_restock'
                                    ? 'bg-rose-500/15 text-rose-900'
                                    : 'bg-gold/25 text-ink',
                              )}
                            >
                              {ev.dossierStatus.replace(/_/g, ' ')}
                            </span>
                          )}
                          {ev?.requiresQuebecBilingualPack && (
                            <span className="px-2 py-0.5 rounded-md bg-sky-500/15 text-sky-900 text-[10px] font-bold">
                              QC Loi 96 Bilingual Required
                            </span>
                          )}
                          {ev?.requiresDevelopmentPortal && (
                            <span className="px-2 py-0.5 rounded-md bg-violet-500/15 text-violet-900 text-[10px] font-bold">
                              QR Portal Staged
                            </span>
                          )}
                        </div>

                        <div className="flex flex-wrap items-center gap-2">
                          <button
                            type="button"
                            disabled={runningIntakeId === order.id}
                            onClick={() => handleRunIntake(order.id)}
                            className="px-3.5 py-1.5 rounded-xl bg-gold text-ink text-[10px] font-black uppercase tracking-wider hover:bg-bronze hover:text-paper flex items-center gap-1.5"
                          >
                            <Play size={12} />
                            <span>{runningIntakeId === order.id ? 'Evaluating...' : 'Run Arty Intake'}</span>
                          </button>
                          <button
                            type="button"
                            onClick={() => handleCopy(`admin-${order.id}`, adminCopySummary)}
                            className="px-3.5 py-1.5 rounded-xl neu-button text-[10px] font-black uppercase tracking-wider text-ink hover:text-gold flex items-center gap-1.5"
                          >
                            <Copy size={12} />
                            <span>Copy #admin Quote Figures</span>
                          </button>
                          {ev?.stagedQuoteMarkdown && (
                            <button
                              type="button"
                              onClick={() => handleCopy(`md-${order.id}`, ev.stagedQuoteMarkdown)}
                              className="px-3.5 py-1.5 rounded-xl neu-button text-[10px] font-black uppercase tracking-wider text-ink hover:text-gold flex items-center gap-1.5"
                            >
                              <Download size={12} />
                              <span>Copy Full Dossier (.md)</span>
                            </button>
                          )}
                        </div>
                      </div>

                      <div className="text-xs text-ink/75 flex flex-wrap gap-x-6 gap-y-1">
                        <span>
                          <strong>Client:</strong> {order.client.companyName} ({order.client.contactPerson} · {order.client.email})
                        </span>
                        <span>
                          <strong>Province / Locale:</strong> {order.province || order.client.province || 'CA'} / {order.locale.toUpperCase()}
                        </span>
                        {order.timeline?.requestedDeliveryDate && (
                          <span>
                            <strong>Requested Delivery:</strong> {order.timeline.requestedDeliveryDate}
                          </span>
                        )}
                      </div>

                      {ev && (
                        <>
                          {/* KPI Financial & Cash-Flow Grid */}
                          <div className="grid grid-cols-2 md:grid-cols-5 gap-3">
                            <div className="p-3.5 rounded-2xl neu-pressed space-y-1">
                              <span className="text-[10px] font-bold uppercase text-ink/50 block">Net Revenue</span>
                              <p className="text-base font-black text-ink font-mono">
                                ${(ev.netRevenueCad ?? ev.quotedSubtotalCad).toFixed(2)} CAD
                              </p>
                              <span className="text-[10px] text-ink/60 block">
                                Tax est: ${(ev.taxPreview?.totalTaxCad ?? 0).toFixed(2)}
                              </span>
                            </div>

                            <div className="p-3.5 rounded-2xl neu-pressed space-y-1">
                              <span className="text-[10px] font-bold uppercase text-ink/50 block">Total Order COGS</span>
                              <p className="text-base font-black text-ink font-mono">
                                ${ev.totalCogsCad.toFixed(2)} CAD
                              </p>
                              <span className="text-[10px] text-ink/60 block">
                                Direct Raw+Pkg: ${(ev.directMaterialsAndPackagingCogsCad ?? 0).toFixed(2)}
                              </span>
                            </div>

                            <div className="p-3.5 rounded-2xl neu-pressed space-y-1">
                              <span className="text-[10px] font-bold uppercase text-ink/50 block">Gross Margin</span>
                              <p
                                className={cn(
                                  'text-base font-black font-mono',
                                  ev.meetsMarginFloor ? 'text-emerald-800' : 'text-rose-700',
                                )}
                              >
                                {ev.grossMarginPct.toFixed(1)}%
                              </p>
                              <span className="text-[10px] text-ink/60 block">
                                Profit ${ev.estimatedGrossProfitCad.toFixed(2)} {ev.meetsMarginFloor ? '(>=70% OK)' : '(LOW MARGIN)'}
                              </span>
                            </div>

                            <div className="p-3.5 rounded-2xl neu-pressed space-y-1">
                              <span className="text-[10px] font-bold uppercase text-ink/50 block">50% B2B Deposit</span>
                              <p className="text-base font-black text-ink font-mono">
                                ${ev.b2bDepositRequiredCad.toFixed(2)} CAD
                              </p>
                              <span
                                className={cn(
                                  'text-[10px] font-bold block',
                                  ev.b2bDepositCoversDirectCogs ? 'text-emerald-800' : 'text-rose-700',
                                )}
                              >
                                {ev.b2bDepositCoversDirectCogs
                                  ? 'Covers 100% Direct COGS'
                                  : `Cash-Flow Gap: $${(ev.depositCashFlowGapCad ?? 0).toFixed(2)}`}
                              </span>
                            </div>

                            <div className="p-3.5 rounded-2xl neu-pressed space-y-1">
                              <span className="text-[10px] font-bold uppercase text-ink/50 block">Production &amp; Ship</span>
                              <p className="text-base font-black text-ink font-mono">
                                {ev.earliestPossibleDeliveryDate}
                              </p>
                              <span
                                className={cn(
                                  'text-[10px] font-bold block',
                                  ev.cureFeasible ? 'text-emerald-800' : 'text-amber-800',
                                )}
                              >
                                Pour {ev.totalUnitsToProduce ?? ev.totalUnits} / Stock {ev.totalFinishedStockAvailable ?? 0} ({ev.maxCureTimeDays}d cure)
                              </span>
                            </div>
                          </div>

                          {ev.timelineWarning && (
                            <div className="p-3.5 rounded-2xl bg-amber-500/10 border border-amber-500/30 text-amber-950 text-xs font-semibold flex items-start gap-2">
                              <AlertTriangle size={15} className="shrink-0 mt-0.5" />
                              <span>{ev.timelineWarning}</span>
                            </div>
                          )}

                          {/* Line-by-line Stock vs Production & COGS */}
                          <div className="overflow-x-auto rounded-2xl border border-ink/10 bg-white/60">
                            <table className="w-full text-left text-[11px]">
                              <thead className="bg-ink/5 font-black uppercase tracking-wider text-ink/60">
                                <tr>
                                  <th className="p-2.5">SKU / Formula</th>
                                  <th className="p-2.5">Qty</th>
                                  <th className="p-2.5">Stock / Pour</th>
                                  <th className="p-2.5">Unit COGS</th>
                                  <th className="p-2.5">Quoted Unit</th>
                                  <th className="p-2.5">Margin</th>
                                  <th className="p-2.5">Cure</th>
                                </tr>
                              </thead>
                              <tbody className="divide-y divide-ink/5">
                                {ev.lineEvaluations.map((line, idx) => (
                                  <tr key={`${line.sku}-${idx}`}>
                                    <td className="p-2.5">
                                      <div className="font-mono font-bold text-ink">{line.sku}</div>
                                      <div className="text-ink/60">{line.formulationName}</div>
                                    </td>
                                    <td className="p-2.5 font-mono font-bold">{line.quantity}</td>
                                    <td className="p-2.5 font-mono">
                                      {line.finishedStockAvailable ?? 0} ready /{' '}
                                      <span className="font-bold text-bronze">{line.unitsToProduce ?? line.quantity} pour</span>
                                    </td>
                                    <td className="p-2.5 font-mono">${line.unitTotalCogsCad.toFixed(2)}</td>
                                    <td className="p-2.5 font-mono">${line.quotedUnitPriceCad.toFixed(2)}</td>
                                    <td
                                      className={cn(
                                        'p-2.5 font-mono font-bold',
                                        line.meetsMarginFloor ? 'text-emerald-800' : 'text-rose-700',
                                      )}
                                    >
                                      {line.grossMarginPct.toFixed(1)}%
                                    </td>
                                    <td className="p-2.5 font-mono">{line.cureTimeDays}d</td>
                                  </tr>
                                ))}
                              </tbody>
                            </table>
                          </div>

                          {/* Shortfalls & Restock Shopping List */}
                          {ev.hasShortfalls && (
                            <div className="p-4 rounded-2xl bg-rose-500/8 border border-rose-500/25 space-y-2">
                              <div className="text-xs font-black uppercase tracking-wider text-rose-900 flex items-center gap-2">
                                <Boxes size={14} />
                                <span>Procurement Shortfall &amp; Restock Shopping List ({ev.shortfalls.length})</span>
                              </div>
                              <div className="grid grid-cols-1 md:grid-cols-2 gap-2">
                                {ev.shortfalls.map((sf, idx) => (
                                  <div
                                    key={`${sf.itemName}-${idx}`}
                                    className="p-2.5 rounded-xl bg-paper border border-rose-500/20 text-[11px] flex items-center justify-between gap-2"
                                  >
                                    <div>
                                      <span className="font-bold text-ink block">{sf.itemName}</span>
                                      <span className="text-ink/60">
                                        Need +{sf.shortfallQty} {sf.unit} · {sf.suggestedVendor || 'Studio Supplier'} (~{sf.supplierLeadDays ?? 7}d lead)
                                      </span>
                                    </div>
                                    <span className="font-mono font-bold text-rose-800 shrink-0">
                                      ${sf.estimatedReorderCostCad.toFixed(2)}
                                    </span>
                                  </div>
                                ))}
                              </div>
                            </div>
                          )}
                        </>
                      )}
                    </div>
                  );
                })}
              </div>
            )}
          </div>

          {/* Internal Outbound Review Queue */}
          <div className="neu-flat rounded-[2.5rem] p-8 space-y-5 border border-white/50">
            <div>
              <h3 className="text-xl font-black text-ink">
                Internal Outbound Review Queue ({mergedOutboundQueue.length})
              </h3>
              <p className="text-xs text-ink/60 mt-1">
                Ready-to-review internal dossiers, procurement alerts, and compliance packs. Nothing leaves this queue automatically.
              </p>
            </div>

            {mergedOutboundQueue.length === 0 ? (
              <div className="p-6 rounded-2xl neu-pressed text-xs text-ink/60 text-center">
                No queued internal review items yet.
              </div>
            ) : (
              <div className="space-y-3">
                {mergedOutboundQueue.map((item) => (
                  <div
                    key={item.id}
                    className="p-5 rounded-2xl bg-paper/80 border border-ink/10 flex flex-col lg:flex-row lg:items-center justify-between gap-4"
                  >
                    <div className="space-y-1.5 min-w-0">
                      <div className="flex flex-wrap items-center gap-2">
                        <span className="px-2 py-0.5 rounded-md bg-ink text-paper text-[10px] font-black uppercase">
                          {item.kind.replace(/_/g, ' ')}
                        </span>
                        <span className="text-sm font-black text-ink">{item.title}</span>
                        <span
                          className={cn(
                            'px-2 py-0.5 rounded-md text-[10px] font-bold uppercase',
                            item.status === 'resolved'
                              ? 'bg-emerald-500/20 text-emerald-950'
                              : item.status === 'approved_copied'
                                ? 'bg-sky-500/20 text-sky-950'
                                : 'bg-amber-500/20 text-amber-950',
                          )}
                        >
                          {item.status.replace(/_/g, ' ')}
                        </span>
                        <span className="px-2 py-0.5 rounded-md bg-rose-500/10 text-rose-900 text-[10px] font-bold">
                          Internal Only · No Auto-Send
                        </span>
                      </div>
                      <p className="text-xs text-ink/70">{item.summary}</p>
                    </div>

                    <div className="flex flex-wrap items-center gap-2 shrink-0">
                      {item.markdownContent && (
                        <button
                          type="button"
                          onClick={() => handleCopy(`out-${item.id}`, item.markdownContent || item.summary)}
                          className="px-3 py-1.5 rounded-xl neu-button text-[10px] font-black uppercase text-ink hover:text-gold flex items-center gap-1"
                        >
                          <Copy size={12} />
                          <span>Copy</span>
                        </button>
                      )}
                      {item.status !== 'approved_copied' && (
                        <button
                          type="button"
                          disabled={updatingOutboundId === item.id}
                          onClick={() => handleOutboundStatus(item.id, 'approved_copied')}
                          className="px-3 py-1.5 rounded-xl bg-gold/30 text-ink text-[10px] font-black uppercase hover:bg-gold"
                        >
                          Mark Copied
                        </button>
                      )}
                      {item.status !== 'resolved' && (
                        <button
                          type="button"
                          disabled={updatingOutboundId === item.id}
                          onClick={() => handleOutboundStatus(item.id, 'resolved')}
                          className="px-3 py-1.5 rounded-xl bg-emerald-500/20 text-emerald-950 text-[10px] font-black uppercase hover:bg-emerald-500/30"
                        >
                          Resolve
                        </button>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      )}

      {/* TAB 4: THREE LIVE REFERENCE LOOKUP TABLES */}
      {subTab === 'tables' && opsData?.referenceData && (
        <div className="space-y-6">
          {/* Table 3: Studio Pricing, 50% Deposit & Cure Lead-Time Rules */}
          <div className="neu-flat rounded-[2.5rem] p-8 space-y-5 border border-white/50">
            <div>
              <p className="text-[10px] font-black uppercase tracking-widest text-gold">
                Lookup Table #3 · Authoritative Financial &amp; Production Rules
              </p>
              <h3 className="text-xl font-black text-ink mt-1">
                Pricing Rules, 50% B2B Deposit, 70% Margin Floor &amp; Cure Windows
              </h3>
            </div>

            <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
              <div className="p-4 rounded-2xl neu-pressed">
                <span className="text-[10px] font-bold uppercase text-ink/50 block">B2B Required Deposit</span>
                <p className="text-lg font-black text-ink font-mono">
                  {opsData.referenceData.pricingRules.b2bDepositPct}% Upfront
                </p>
              </div>
              <div className="p-4 rounded-2xl neu-pressed">
                <span className="text-[10px] font-bold uppercase text-ink/50 block">Studio Margin Floor</span>
                <p className="text-lg font-black text-emerald-800 font-mono">
                  {opsData.referenceData.pricingRules.grossMarginFloorPct}% Gross (Target {opsData.referenceData.pricingRules.customTargetMarginPct}%)
                </p>
              </div>
              <div className="p-4 rounded-2xl neu-pressed">
                <span className="text-[10px] font-bold uppercase text-ink/50 block">Labor &amp; Overhead Allocation</span>
                <p className="text-lg font-black text-ink font-mono">
                  ${opsData.referenceData.pricingRules.hourlyLaborRateCad}/hr · ${opsData.referenceData.pricingRules.allocatedOverheadPerUnitCad}/unit
                </p>
              </div>
              <div className="p-4 rounded-2xl neu-pressed">
                <span className="text-[10px] font-bold uppercase text-ink/50 block">Standard Cure Windows</span>
                <p className="text-xs font-bold text-ink mt-1">
                  CP Soap {opsData.referenceData.pricingRules.cureWindowsDays.coldProcessSoap}d · Stone {opsData.referenceData.pricingRules.cureWindowsDays.stoneCastSoap}d · B2B {opsData.referenceData.pricingRules.cureWindowsDays.b2bClosingBoxes}d · Balms {opsData.referenceData.pricingRules.cureWindowsDays.serumsAndBalms}d
                </p>
              </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-4 gap-3">
              {opsData.referenceData.pricingRules.volumeTiers.map((tier) => (
                <div key={tier.id} className="p-4 rounded-2xl bg-paper border border-ink/10 space-y-1">
                  <div className="text-xs font-black text-ink">{tier.label}</div>
                  <div className="text-[11px] font-mono text-bronze">
                    Discount: {tier.discountPctOffBase}% · Floor Margin: {tier.targetMarginPct}%
                  </div>
                  <div className="text-[11px] text-ink/60">Edition: {tier.boxEdition}</div>
                </div>
              ))}
            </div>
          </div>

          {/* Table 1: SKU -> BOM & Per-Unit COGS Across All Tracks */}
          <div className="neu-flat rounded-[2.5rem] p-8 space-y-4 border border-white/50">
            <div>
              <p className="text-[10px] font-black uppercase tracking-widest text-gold">
                Lookup Table #1 · Catalog SKU -&gt; Formulation &amp; Packaging BOM
              </p>
              <h3 className="text-xl font-black text-ink mt-1">
                All-Track SKU COGS, Gross Margin &amp; 50% Deposit Schedule ({opsData.referenceData.cogsSummary.skus.length} SKUs)
              </h3>
            </div>

            <div className="overflow-x-auto rounded-2xl border border-ink/10 bg-paper/70">
              <table className="w-full text-left text-xs">
                <thead className="bg-ink/5 text-[10px] font-black uppercase tracking-wider text-ink/60">
                  <tr>
                    <th className="p-3">SKU &amp; Track</th>
                    <th className="p-3">Product &amp; BOM Components</th>
                    <th className="p-3">Raw COGS</th>
                    <th className="p-3">Pkg COGS</th>
                    <th className="p-3">Labor+OH</th>
                    <th className="p-3">Total COGS</th>
                    <th className="p-3">Unit Price</th>
                    <th className="p-3">Margin %</th>
                    <th className="p-3">50% B2B Deposit</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-ink/5">
                  {opsData.referenceData.cogsSummary.skus.map((skuRow) => {
                    const bom = opsData.referenceData.skuBomCatalog.find((b) => b.sku === skuRow.sku);
                    return (
                      <tr key={skuRow.sku} className="align-top hover:bg-ink/[0.02]">
                        <td className="p-3 whitespace-nowrap">
                          <div className="font-mono font-bold text-ink">{skuRow.sku}</div>
                          <span className="text-[10px] font-black uppercase text-bronze">{skuRow.track}</span>
                        </td>
                        <td className="p-3 min-w-[240px]">
                          <div className="font-bold text-ink">{skuRow.name}</div>
                          {bom && (
                            <div className="text-[11px] text-ink/65 mt-0.5">
                              {bom.finishedUnitWeight} · {bom.cureTimeDays}d cure · {bom.rawBom.length} raw / {bom.packagingBom.length} pkg items
                            </div>
                          )}
                        </td>
                        <td className="p-3 font-mono">${skuRow.unitRawCostCad.toFixed(2)}</td>
                        <td className="p-3 font-mono">${skuRow.unitPackagingCostCad.toFixed(2)}</td>
                        <td className="p-3 font-mono">${skuRow.unitLaborOverheadCad.toFixed(2)}</td>
                        <td className="p-3 font-mono font-bold">${skuRow.unitTotalCogsCad.toFixed(2)}</td>
                        <td className="p-3 font-mono font-bold">${skuRow.priceCad.toFixed(2)}</td>
                        <td
                          className={cn(
                            'p-3 font-mono font-bold',
                            skuRow.grossMarginPct >= 70 ? 'text-emerald-800' : 'text-rose-700',
                          )}
                        >
                          {skuRow.grossMarginPct.toFixed(1)}%
                        </td>
                        <td className="p-3 font-mono font-bold text-bronze">
                          ${skuRow.b2b50PctDepositPerUnitCad.toFixed(2)}
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </div>

          {/* Table 2: Standardized Inventory (g/ml/pcs + Reorder Floors) */}
          <div className="neu-flat rounded-[2.5rem] p-8 space-y-4 border border-white/50">
            <div>
              <p className="text-[10px] font-black uppercase tracking-widest text-gold">
                Lookup Table #2 · Standardized Studio Inventory &amp; Reorder Floors
              </p>
              <h3 className="text-xl font-black text-ink mt-1">
                Live Normalized Materials &amp; Packaging ({opsData.referenceData.standardizedInventory.length} Items)
              </h3>
            </div>

            <div className="overflow-x-auto rounded-2xl border border-ink/10 bg-paper/70">
              <table className="w-full text-left text-xs">
                <thead className="bg-ink/5 text-[10px] font-black uppercase tracking-wider text-ink/60">
                  <tr>
                    <th className="p-3">Item &amp; Category</th>
                    <th className="p-3">Raw Logged</th>
                    <th className="p-3">Normalized Stock</th>
                    <th className="p-3">Reorder Floor</th>
                    <th className="p-3">Normalized Unit Cost</th>
                    <th className="p-3">Status</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-ink/5">
                  {opsData.referenceData.standardizedInventory.map((inv) => (
                    <tr key={inv.id} className="hover:bg-ink/[0.02]">
                      <td className="p-3">
                        <div className="font-bold text-ink">{inv.item}</div>
                        <div className="text-[10px] uppercase text-ink/50">{inv.category}</div>
                      </td>
                      <td className="p-3 font-mono text-ink/70">
                        {inv.originalStock} {inv.originalUnit}
                      </td>
                      <td className="p-3 font-mono font-bold text-ink">
                        {inv.normalizedStock.toLocaleString()} {inv.normalizedUnit}
                      </td>
                      <td className="p-3 font-mono">
                        {inv.reorderThreshold.toLocaleString()} {inv.normalizedUnit}
                      </td>
                      <td className="p-3 font-mono">
                        ${inv.costPerNormalizedUnit.toFixed(4)} / {inv.normalizedUnit}
                      </td>
                      <td className="p-3">
                        <span
                          className={cn(
                            'px-2 py-0.5 rounded-md text-[10px] font-black uppercase',
                            inv.lowStock
                              ? 'bg-rose-500/15 text-rose-900'
                              : 'bg-emerald-500/15 text-emerald-900',
                          )}
                        >
                          {inv.lowStock ? 'Restock Needed' : 'Healthy'}
                        </span>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}

      {/* TAB 3: B2B + SKINCARE AGREEMENT & MULTI-PRODUCT CATALOG */}
      {subTab === 'agreement' && editableCatalog && (
        <div className="space-y-6">
          <div className="neu-flat rounded-[2.5rem] p-8 space-y-5 border border-white/50">
            <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-4">
              <div>
                <p className="text-[10px] font-black uppercase tracking-widest text-gold">
                  Primary Brand Face: B2B Builders, Architects &amp; Developers · Catalog v{editableCatalog.catalogVersion}
                </p>
                <h3 className="text-xl font-black text-ink mt-1">
                  Canonical SKU Agreement Table (B2B + Multi-Product Eczema &amp; Menopause)
                </h3>
                <p className="text-xs text-ink/60 mt-1">
                  Set real availability statuses (<code className="font-mono">preorder</code>, <code className="font-mono">sample_only</code>, <code className="font-mono">in_development</code>, <code className="font-mono">in_stock</code>), Law 96 French names, CAD prices, and cure lead days. StudioOS remains authoritative for commercial &amp; batch truth while Storefront keeps its editorial images.
                </p>
              </div>
              <div className="flex flex-wrap gap-2.5 shrink-0">
                <button
                  type="button"
                  disabled={isSavingCatalog}
                  onClick={handleSaveCatalog}
                  className={cn(
                    'px-4 py-2.5 rounded-xl text-[10px] font-black uppercase tracking-wider flex items-center gap-2',
                    catalogDirty
                      ? 'bg-ink text-paper hover:bg-gold hover:text-ink'
                      : 'neu-button text-ink/70 hover:text-gold',
                  )}
                >
                  <Save size={13} />
                  <span>{isSavingCatalog ? 'Saving...' : catalogDirty ? 'Save Agreement*' : 'Saved'}</span>
                </button>
                <button
                  type="button"
                  disabled={isPushingCatalog}
                  onClick={handlePushCatalog}
                  className="px-5 py-2.5 bg-gold text-ink rounded-xl text-[10px] font-black uppercase tracking-wider hover:bg-bronze hover:text-paper transition-colors flex items-center gap-2 shadow-sm"
                >
                  <Send size={13} />
                  <span>{isPushingCatalog ? 'Pushing...' : 'Push Catalog to Storefront'}</span>
                </button>
              </div>
            </div>

            {/* Track Filter Pills */}
            <div className="flex flex-wrap gap-2 pt-2">
              {[
                { key: 'all', label: `All SKUs (${trackCounts.all})` },
                { key: 'b2b', label: `B2B Flagship (${trackCounts.b2b})` },
                { key: 'eczema', label: `Eczema Line (${trackCounts.eczema})` },
                { key: 'menopause', label: `Menopause / Say It Plain (${trackCounts.menopause})` },
              ].map((pill) => (
                <button
                  key={pill.key}
                  type="button"
                  onClick={() => setCatalogTrackFilter(pill.key as any)}
                  className={cn(
                    'px-3.5 py-1.5 rounded-xl text-[11px] font-bold transition-all',
                    catalogTrackFilter === pill.key
                      ? 'bg-ink text-paper'
                      : 'neu-button text-ink/70 hover:text-gold',
                  )}
                >
                  {pill.label}
                </button>
              ))}
            </div>

            {/* Add Multi-Product SKU Bar (for Say It Plain / Eczema Expansion) */}
            <form
              onSubmit={handleAddSku}
              className="p-4 rounded-2xl neu-pressed grid grid-cols-1 md:grid-cols-12 gap-3 items-end"
            >
              <div className="md:col-span-2">
                <label className="text-[10px] font-bold uppercase text-ink/50 block mb-1">Track</label>
                <select
                  value={newSkuForm.track}
                  onChange={(e) => setNewSkuForm({ ...newSkuForm, track: e.target.value as StorefrontTrack })}
                  className="w-full px-3 py-2 rounded-xl bg-paper border border-ink/10 text-xs font-semibold text-ink"
                >
                  <option value="menopause">Menopause (Say It Plain)</option>
                  <option value="eczema">Eczema / Sensitive</option>
                  <option value="b2b">B2B Flagship</option>
                </select>
              </div>
              <div className="md:col-span-2">
                <label className="text-[10px] font-bold uppercase text-ink/50 block mb-1">Canonical SKU</label>
                <input
                  type="text"
                  placeholder="LJW-MEN-SERUM-30"
                  value={newSkuForm.sku}
                  onChange={(e) => setNewSkuForm({ ...newSkuForm, sku: e.target.value })}
                  className="w-full px-3 py-2 rounded-xl bg-paper border border-ink/10 text-xs font-mono text-ink"
                />
              </div>
              <div className="md:col-span-2">
                <label className="text-[10px] font-bold uppercase text-ink/50 block mb-1">Storefront Slug</label>
                <input
                  type="text"
                  placeholder="cooling-night-serum"
                  value={newSkuForm.storefrontSlug}
                  onChange={(e) => setNewSkuForm({ ...newSkuForm, storefrontSlug: e.target.value })}
                  className="w-full px-3 py-2 rounded-xl bg-paper border border-ink/10 text-xs font-mono text-ink"
                />
              </div>
              <div className="md:col-span-2">
                <label className="text-[10px] font-bold uppercase text-ink/50 block mb-1">Name (EN)</label>
                <input
                  type="text"
                  placeholder="Thermal Night Serum"
                  value={newSkuForm.nameEn}
                  onChange={(e) => setNewSkuForm({ ...newSkuForm, nameEn: e.target.value })}
                  className="w-full px-3 py-2 rounded-xl bg-paper border border-ink/10 text-xs text-ink"
                />
              </div>
              <div className="md:col-span-2">
                <label className="text-[10px] font-bold uppercase text-ink/50 block mb-1">Nom (FR · Loi 96)</label>
                <input
                  type="text"
                  placeholder="Sérum Nuit Apaisant"
                  value={newSkuForm.nameFr}
                  onChange={(e) => setNewSkuForm({ ...newSkuForm, nameFr: e.target.value })}
                  className="w-full px-3 py-2 rounded-xl bg-paper border border-ink/10 text-xs text-ink"
                />
              </div>
              <div className="md:col-span-1">
                <label className="text-[10px] font-bold uppercase text-ink/50 block mb-1">CAD $</label>
                <input
                  type="number"
                  min={0}
                  step="0.01"
                  value={newSkuForm.priceCad}
                  onChange={(e) => setNewSkuForm({ ...newSkuForm, priceCad: Number(e.target.value) })}
                  className="w-full px-2.5 py-2 rounded-xl bg-paper border border-ink/10 text-xs font-mono text-ink"
                />
              </div>
              <div className="md:col-span-1">
                <button
                  type="submit"
                  className="w-full py-2 px-3 rounded-xl bg-gold text-ink text-[10px] font-black uppercase tracking-wider hover:bg-bronze hover:text-paper flex items-center justify-center gap-1"
                >
                  <Plus size={13} />
                  <span>Add</span>
                </button>
              </div>
            </form>

            {/* SKU Table */}
            <div className="overflow-x-auto rounded-2xl border border-ink/10 bg-paper/70">
              <table className="w-full text-left text-xs">
                <thead className="bg-ink/5 text-[10px] font-black uppercase tracking-wider text-ink/60">
                  <tr>
                    <th className="p-3">SKU &amp; Slug</th>
                    <th className="p-3">Track</th>
                    <th className="p-3">EN / FR Title (Law 96)</th>
                    <th className="p-3">CAD $</th>
                    <th className="p-3">Launch Truth Status</th>
                    <th className="p-3">Stock / Cure</th>
                    <th className="p-3">MOQ</th>
                    <th className="p-3 text-right">Sync</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-ink/5">
                  {filteredProducts.map((item) => (
                    <tr key={item.sku} className="hover:bg-ink/[0.02] align-top">
                      <td className="p-3 space-y-1 min-w-[175px]">
                        <div className="font-mono font-bold text-ink">{item.sku}</div>
                        <div className="font-mono text-[11px] text-ink/60">
                          {item.storefrontSlug} · <span className="text-gold">{item.variantKey}</span>
                        </div>
                      </td>
                      <td className="p-3">
                        <span
                          className={cn(
                            'px-2 py-0.5 rounded-md text-[10px] font-black uppercase',
                            item.track === 'b2b'
                              ? 'bg-gold/25 text-ink'
                              : item.track === 'eczema'
                                ? 'bg-sky-500/15 text-sky-900'
                                : 'bg-rose-500/15 text-rose-900',
                          )}
                        >
                          {item.track}
                        </span>
                      </td>
                      <td className="p-3 space-y-1.5 min-w-[240px]">
                        <input
                          type="text"
                          value={item.nameEn}
                          onChange={(e) => updateSkuField(item.sku, 'nameEn', e.target.value)}
                          className="w-full px-2.5 py-1 rounded-lg bg-paper border border-ink/10 text-xs font-semibold text-ink"
                        />
                        <input
                          type="text"
                          value={item.nameFr}
                          onChange={(e) => updateSkuField(item.sku, 'nameFr', e.target.value)}
                          className="w-full px-2.5 py-1 rounded-lg bg-paper border border-ink/10 text-[11px] text-ink/70"
                        />
                      </td>
                      <td className="p-3 min-w-[90px]">
                        <input
                          type="number"
                          min={0}
                          step="0.5"
                          value={item.priceCad}
                          onChange={(e) => updateSkuField(item.sku, 'priceCad', Number(e.target.value) || 0)}
                          className="w-20 px-2 py-1 rounded-lg bg-paper border border-ink/10 font-mono text-xs text-ink"
                        />
                      </td>
                      <td className="p-3 min-w-[175px]">
                        <select
                          value={item.status}
                          onChange={(e) =>
                            updateSkuField(item.sku, 'status', e.target.value as StorefrontAvailabilityStatus)
                          }
                          className="w-full px-2 py-1 rounded-lg bg-paper border border-ink/10 text-[11px] font-semibold text-ink"
                        >
                          {Object.entries(STATUS_LABELS).map(([val, lbl]) => (
                            <option key={val} value={val}>
                              {lbl}
                            </option>
                          ))}
                        </select>
                      </td>
                      <td className="p-3 min-w-[130px] space-y-1">
                        <div className="flex items-center gap-1">
                          <span className="text-[10px] text-ink/50 w-9">Qty:</span>
                          <input
                            type="number"
                            min={0}
                            value={item.stockAvailable}
                            onChange={(e) =>
                              updateSkuField(item.sku, 'stockAvailable', Math.max(0, Number(e.target.value) || 0))
                            }
                            className="w-16 px-2 py-0.5 rounded-lg bg-paper border border-ink/10 font-mono text-[11px]"
                          />
                        </div>
                        <div className="flex items-center gap-1">
                          <span className="text-[10px] text-ink/50 w-9">Cure:</span>
                          <input
                            type="number"
                            min={0}
                            value={item.cureLeadDays}
                            onChange={(e) =>
                              updateSkuField(item.sku, 'cureLeadDays', Math.max(0, Number(e.target.value) || 0))
                            }
                            className="w-16 px-2 py-0.5 rounded-lg bg-paper border border-ink/10 font-mono text-[11px]"
                          />
                          <span className="text-[10px] text-ink/50">d</span>
                        </div>
                      </td>
                      <td className="p-3">
                        <input
                          type="number"
                          min={1}
                          value={item.moq}
                          onChange={(e) =>
                            updateSkuField(item.sku, 'moq', Math.max(1, Number(e.target.value) || 1))
                          }
                          className="w-14 px-2 py-1 rounded-lg bg-paper border border-ink/10 font-mono text-xs"
                        />
                      </td>
                      <td className="p-3 text-right">
                        <div className="flex items-center justify-end gap-2">
                          <input
                            type="checkbox"
                            checked={item.activeOnStorefront}
                            onChange={(e) =>
                              updateSkuField(item.sku, 'activeOnStorefront', e.target.checked)
                            }
                            title="Include in Storefront sync"
                          />
                          <button
                            type="button"
                            onClick={() => handleRemoveSku(item.sku)}
                            className="p-1.5 rounded-lg text-ink/40 hover:text-rose-700"
                            title="Remove SKU row"
                          >
                            <Trash2 size={13} />
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}

      {/* TAB 4: COPY-PASTEABLE STOREFRONT LLM HANDOFF SPEC */}
      {subTab === 'handoff' && (
        <div className="neu-flat rounded-[2.5rem] p-8 space-y-5 border border-white/50">
          <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
            <div>
              <h3 className="text-xl font-black text-ink">
                Copy-Pasteable Spec for Storefront LLM (<code className="font-mono">ljwellness-vs3</code>)
              </h3>
              <p className="text-xs text-ink/60 mt-1">
                Give this Markdown brief to your Storefront LLM on <code className="font-mono">staging.ljwellness.net</code> so its Express backend implements the exact matching endpoints, HMAC signing, and staging safeguard.
              </p>
            </div>
            <div className="flex flex-wrap items-center gap-2.5 shrink-0">
              <button
                type="button"
                onClick={() => {
                  const blob = new Blob([storefrontHandoffMarkdown], { type: 'text/markdown;charset=utf-8' });
                  const url = URL.createObjectURL(blob);
                  const a = document.createElement('a');
                  a.href = url;
                  a.download = 'STOREFRONT_LLM_HANDOFF_SPEC.md';
                  document.body.appendChild(a);
                  a.click();
                  document.body.removeChild(a);
                  URL.revokeObjectURL(url);
                  toast.success('Downloaded STOREFRONT_LLM_HANDOFF_SPEC.md');
                }}
                className="px-4 py-2.5 neu-button text-ink rounded-xl text-[10px] font-black uppercase tracking-wider hover:text-gold transition-colors flex items-center gap-2 shrink-0"
              >
                <Download size={14} />
                <span>Download .md</span>
              </button>
              <button
                type="button"
                onClick={() => handleCopy('storefront-handoff', storefrontHandoffMarkdown)}
                className="px-5 py-2.5 bg-gold text-ink rounded-xl text-[10px] font-black uppercase tracking-wider hover:bg-bronze hover:text-paper transition-colors flex items-center gap-2 shrink-0"
              >
                {copiedKey === 'storefront-handoff' ? <Check size={14} /> : <Copy size={14} />}
                <span>
                  {copiedKey === 'storefront-handoff' ? 'Copied Spec!' : 'Copy Full Spec (.md)'}
                </span>
              </button>
            </div>
          </div>

          <pre className="p-6 rounded-3xl neu-pressed text-xs font-mono text-ink/85 whitespace-pre-wrap overflow-x-auto max-h-[560px] overflow-y-auto leading-relaxed">
            {storefrontHandoffMarkdown}
          </pre>
        </div>
      )}
    </div>
  );
};
