// ProductTour.jsx — interactive product showcase with auto-rotating screen slideshow.
// Renders 5 stylised product screens inside a browser-frame viewport with
// thumbnails on the side, an auto-advance progress bar, and crossfade transitions.
//
// We only showcase screens that are *fully built* in the real app and that earn
// their slot in a marketing tour. Obras (basic list, no detail page yet) and the
// AI assistant (already represented in the dedicated "IA" section of the landing
// via ChatPreviewCard) are intentionally omitted.
//
// The five screens mirror the real ConstructHub admin + portal UI:
//   1. Painel        → frontend/src/features/dashboard/layouts/construction-v1.tsx
//   2. Compras       → frontend/src/routes/_app/compras/index.tsx
//   3. Catálogo      → frontend/src/routes/_app/catalog/index.tsx
//   4. Faturação     → frontend/src/routes/_app/faturacao/index.tsx
//   5. Portal B2B    → frontend/src/routes/portal/catalog.tsx + portal-shell.tsx
//
// Visual rhythm matches the real app: shadcn neutrals + indigo accent (#4F6EF7),
// rounded-xl cards, sticky white/85 backdrop-blur header, h-14 top row, real
// nav labels (Painel · Catálogo · Clientes · Armazém · Compras · Vendas · Faturação · Relatórios).

const TOUR_INDIGO = '#4F6EF7';
const TOUR_INDIGO_SOFT = '#EEF1FF';

// ─── Browser frame wrapper ──────────────────────────────────────────
function BrowserFrame({ url, children, dark }) {
  return (
    <div className={`rounded-xl overflow-hidden border ${dark ? 'border-zinc-700' : 'border-zinc-200'}`}
         style={{ boxShadow: '0 30px 60px -20px rgba(15,15,20,0.18), 0 12px 24px -10px rgba(15,15,20,0.10)' }}>
      <div className={`h-9 flex items-center px-3 gap-2 border-b ${dark ? 'bg-zinc-900 border-zinc-700' : 'bg-zinc-50/80 border-zinc-100'}`}>
        <span className="h-2.5 w-2.5 rounded-full shrink-0" style={{ background: '#FF5F57' }}></span>
        <span className="h-2.5 w-2.5 rounded-full shrink-0" style={{ background: '#FEBC2E' }}></span>
        <span className="h-2.5 w-2.5 rounded-full shrink-0" style={{ background: '#28C840' }}></span>
        <div className={`flex-1 min-w-0 h-5 rounded mx-3 text-[10.5px] flex items-center justify-center gap-1.5 ${dark ? 'bg-zinc-800 text-zinc-400' : 'bg-white text-zinc-400 border border-zinc-100'}`}>
          <L name="lock" className="w-2.5 h-2.5 shrink-0" /><span className="truncate">{url}</span>
        </div>
      </div>
      <div className="bg-white overflow-x-auto no-scrollbar h-[400px] sm:h-[480px] lg:h-[560px]">
        <div className="min-w-[640px] h-full">
          {children}
        </div>
      </div>
    </div>
  );
}

// ─── Tiny inline sparkline ─────────────────────────────────────────
function Sparkline({ data, color = TOUR_INDIGO, width = 80, height = 24 }) {
  const max = Math.max(...data);
  const min = Math.min(...data);
  const range = max - min || 1;
  const step = width / (data.length - 1);
  const points = data.map((v, i) => `${i * step},${height - ((v - min) / range) * height}`).join(' ');
  return (
    <svg width={width} height={height} className="overflow-visible">
      <polyline points={points} fill="none" stroke={color} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
}

// ─── ConstructHub logomark (real SVG from frontend/src/components/brand/logomark.tsx) ─
function Logomark({ size = 16 }) {
  return (
    <svg viewBox="0 0 60 48" width={size * 1.25} height={size} fill="currentColor" aria-hidden="true">
      <rect x="2" y="10" width="8" height="28" rx="1.5" />
      <rect x="12" y="10" width="12" height="7" rx="1.5" />
      <rect x="12" y="31" width="12" height="7" rx="1.5" />
      <rect x="30" y="10" width="8" height="28" rx="1.5" />
      <rect x="40" y="10" width="8" height="28" rx="1.5" />
      <rect x="50" y="20" width="8" height="8" rx="1.5" />
    </svg>
  );
}

// ─── Shared app header (mirrors components/layout/app-header.tsx) ───
// h-14 sticky top bar, max-w-1400 inner, brand + horizontal nav + right cluster.
// Nav items map 1:1 to NAV_ITEMS in lib/nav-config.ts.
const APP_NAV = [
  { l: 'Painel',     i: 'layout-dashboard' },
  { l: 'Catálogo',   i: 'package' },
  { l: 'Clientes',   i: 'users',     chev: true },
  { l: 'Armazém',    i: 'warehouse' },
  { l: 'Compras',    i: 'truck' },
  { l: 'Vendas',     i: 'shopping-cart' },
  { l: 'Faturação',  i: 'file-text' },
  { l: 'Relatórios', i: 'bar-chart-3' },
];

function AppHeader({ active }) {
  return (
    <div className="h-14 border-b border-zinc-100 bg-white/95 backdrop-blur-md flex items-center px-4 gap-3">
      {/* Brand */}
      <div className="flex items-center gap-2 text-zinc-900">
        <Logomark size={16} />
        <span className="text-[14px] font-semibold tracking-tight">ConstructHub</span>
      </div>

      {/* Horizontal nav */}
      <nav className="flex items-center gap-0.5 ml-2">
        {APP_NAV.map(n => {
          const a = n.l === active;
          return (
            <span key={n.l}
                  className={'h-9 px-2.5 rounded-md text-[12px] inline-flex items-center gap-1.5 whitespace-nowrap ' +
                    (a ? 'bg-zinc-100 text-zinc-900 font-medium' : 'text-zinc-500')}>
              <L name={n.i} className="w-3 h-3 shrink-0" />
              <span>{n.l}</span>
              {n.chev && <L name="chevron-down" className="w-2.5 h-2.5 opacity-60" />}
            </span>
          );
        })}
      </nav>

      <span className="flex-1"></span>

      {/* Right cluster: search · lang · bell · help · avatar */}
      <div className="hidden md:flex items-center gap-1.5 h-9 px-2.5 rounded-md border border-zinc-200 text-[11.5px] text-zinc-400">
        <span>Procurar</span>
        <kbd className="inline-flex items-center rounded border border-zinc-200 bg-zinc-50 px-1 text-[9px] font-medium">⌘K</kbd>
      </div>
      <span className="h-7 w-7 rounded-md grid place-items-center text-zinc-500"><L name="languages" className="w-3.5 h-3.5" /></span>
      <span className="h-7 w-7 rounded-md grid place-items-center text-zinc-500 relative">
        <L name="bell" className="w-3.5 h-3.5" />
        <span className="absolute -right-0.5 -top-0.5 h-3 min-w-3 px-0.5 grid place-items-center rounded-full bg-red-500 text-[8px] font-bold text-white">3</span>
      </span>
      <span className="h-7 w-7 rounded-md grid place-items-center text-zinc-500"><L name="circle-help" className="w-3.5 h-3.5" /></span>
      <span className="text-[10.5px] text-zinc-400 hidden lg:inline">owner</span>
      <span className="h-7 w-7 rounded-full bg-zinc-200 text-[9px] grid place-items-center font-semibold text-zinc-700">JP</span>
    </div>
  );
}

// ─── Status pill (mirrors design-system tone tokens) ───
function StatusPill({ tone, label }) {
  const bg = { neutral:'#F4F4F5', info:'#F0F9FF', success:'#ECFDF5', warning:'#FFFBEB', destructive:'#FEF2F2' }[tone];
  const fg = { neutral:'#3F3F46', info:'#0369A1', success:'#047857', warning:'#B45309', destructive:'#B91C1C' }[tone];
  const dot = { neutral:'#A1A1AA', info:'#0EA5E9', success:'#10B981', warning:'#F59E0B', destructive:'#EF4444' }[tone];
  return (
    <span className="inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 text-[10.5px] font-medium"
          style={{ background: bg, color: fg }}>
      <span className="h-1.5 w-1.5 rounded-full" style={{ background: dot }}></span>
      {label}
    </span>
  );
}

// ─── KPI tile (mirrors components/shared/kpi-card.tsx) ───
function KpiTile({ label, value, icon, iconBg = '#EEF1FF', iconColor = TOUR_INDIGO, sparkData, sparkColor, description, highlight }) {
  return (
    <div className={'rounded-xl border bg-white p-3 shadow-sm ' + (highlight ? 'border-red-200 bg-red-50/40' : 'border-zinc-200')}>
      <div className="flex items-center justify-between">
        <p className="text-[9px] font-semibold uppercase tracking-widest text-zinc-500">{label}</p>
        <div className="rounded-md p-1" style={{ background: highlight ? '#FEE2E2' : iconBg }}>
          <L name={icon} className="w-3 h-3" style={{ color: highlight ? '#B91C1C' : iconColor }} />
        </div>
      </div>
      <p className={'mt-1.5 text-[18px] font-semibold tracking-tight ' + (highlight ? 'text-red-700' : 'text-zinc-900')}>{value}</p>
      {sparkData && (
        <div className="mt-1.5">
          <Sparkline data={sparkData} color={sparkColor || iconColor} width={64} height={18} />
        </div>
      )}
      {description && <p className="mt-1 text-[10px] text-zinc-500">{description}</p>}
    </div>
  );
}

// ══════════════════════════════════════════════════════════════════
// SCREEN 1 — Painel (Dashboard)
// Mirrors features/dashboard/layouts/construction-v1.tsx:
//   • 5 KPI tiles (Receita mensal / A receber / Stock / Orçamentos / Alertas)
//   • Tendência de receita — 6-month bar chart
//   • 3 quick-link cards (Vendas / Stock / Recebimentos)
// ══════════════════════════════════════════════════════════════════
function DashboardScreen() {
  // Sample 6-month series in cents → euros (compact format like the real app).
  const revenueMonths = [
    { m: 'Dez', v: 38 },
    { m: 'Jan', v: 42 },
    { m: 'Fev', v: 51 },
    { m: 'Mar', v: 48 },
    { m: 'Abr', v: 67 },
    { m: 'Mai', v: 82 },
  ];
  const maxRev = Math.max(...revenueMonths.map(r => r.v));

  return (
    <div className="h-full flex flex-col">
      <div className="flex-1 p-4 overflow-hidden">
        {/* Page header */}
        <div className="mb-3">
          <h1 className="text-[17px] font-semibold tracking-tight">Bem-vindo, João</h1>
          <p className="mt-0.5 text-[11.5px] text-zinc-500">Painel de controlo — segunda-feira, 18 de maio de 2026</p>
        </div>

        {/* KPI strip — 5 cards, real labels */}
        <div className="grid grid-cols-5 gap-2 mb-3">
          <KpiTile label="Receita mensal" value="82k €" icon="trending-up"
                   sparkData={revenueMonths.map(r => r.v)} description="mês corrente" />
          <KpiTile label="A receber" value="34k €" icon="wallet" iconBg="#FEF3C7" iconColor="#B45309"
                   description="faturas por pagar" highlight />
          <KpiTile label="Valor em stock" value="218k €" icon="package" iconBg="#F0F9FF" iconColor="#0EA5E9"
                   description="custo total" />
          <KpiTile label="Orçamentos" value="12" icon="shopping-cart" iconBg="#ECFDF5" iconColor="#10B981"
                   description="à espera de confirmação" />
          <KpiTile label="Alertas críticos" value="4" icon="alert-triangle" iconBg="#FEF2F2" iconColor="#EF4444"
                   description="stock abaixo do mínimo" highlight />
        </div>

        {/* Tendência de receita */}
        <div className="rounded-xl border border-zinc-200 bg-white p-3 shadow-sm mb-3">
          <div className="flex items-center justify-between mb-2">
            <div className="text-[12px] font-semibold">Tendência de receita</div>
            <span className="text-[10.5px] font-medium" style={{ color: TOUR_INDIGO }}>Ver relatório completo →</span>
          </div>
          <div className="flex items-end gap-3 pl-2" style={{ height: 90 }}>
            {revenueMonths.map((r, i) => {
              const h = (r.v / maxRev) * 100;
              return (
                <div key={i} className="flex-1 flex flex-col items-center gap-1">
                  <div className="w-full rounded-t" style={{ height: `${h}%`, background: i === revenueMonths.length - 1 ? TOUR_INDIGO : '#27272A', minHeight: 4 }}></div>
                  <span className="text-[9px] text-zinc-400">{r.m}</span>
                </div>
              );
            })}
          </div>
        </div>

        {/* Quick links */}
        <div className="grid grid-cols-3 gap-2.5">
          {[
            { i: 'bar-chart-3', t: 'Relatório de vendas',   s: 'Análise por período e produto' },
            { i: 'package',     t: 'Avaliação de stock',     s: 'Valor de stock por armazém' },
            { i: 'wallet',      t: 'Conta corrente',         s: 'Recebimentos e pendentes' },
          ].map((q, i) => (
            <div key={i} className="rounded-xl border border-zinc-200 bg-white p-3 shadow-sm flex items-center gap-3">
              <L name={q.i} className="w-4 h-4" style={{ color: TOUR_INDIGO }} />
              <div className="min-w-0">
                <div className="text-[11.5px] font-medium truncate">{q.t}</div>
                <div className="text-[10px] text-zinc-500 truncate">{q.s}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// ══════════════════════════════════════════════════════════════════
// SCREEN 2 — Compras (Purchase Orders)
// Mirrors routes/_app/compras/index.tsx:
//   • Page header "Compras" + subtitle + Filtros / Nova encomenda
//   • 4 KPIs (Encomendas / Valor total / Atrasadas / Lead time)
//   • Search input INSIDE table card header
//   • Columns: Nº · Fornecedor · Emissão · Prev. entrega · Estado · Linhas · Total
//   • Status pills with dot (Rascunho/Aberta/Confirmada/Parcial/Recebida/Cancelada)
// ══════════════════════════════════════════════════════════════════
function ComprasScreen() {
  const rows = [
    ['EC-0241', 'Cimentos Mafra',  '12 mai', '20 mai', 'Aberta',     'info',        4, '4 280 €'],
    ['EC-0240', 'Tintas do Norte', '11 mai', '22 mai', 'Confirmada', 'info',        2, '1 940 €'],
    ['EC-0239', 'Sika Portugal',   '10 mai', '21 mai', 'Parcial',    'warning',     6, '3 510 €'],
    ['EC-0238', 'Tabique, Lda.',   '08 mai', '14 mai', 'Recebida',   'success',     3,   '986 €'],
    ['EC-0237', 'Cimentos Mafra',  '07 mai', '12 mai', 'Recebida',   'success',     5, '5 240 €'],
    ['EC-0236', 'Pladur Iberia',   '05 mai', '11 mai', 'Recebida',   'success',     2, '1 120 €'],
    ['EC-0235', 'Tabique, Lda.',   '03 mai', '09 mai', 'Cancelada',  'neutral',     1,   '180 €'],
  ];

  return (
    <div className="h-full flex flex-col">
      <div className="flex-1 p-4 overflow-hidden flex flex-col gap-3">
        {/* Page header */}
        <div className="flex items-start justify-between">
          <div>
            <h1 className="text-[17px] font-semibold tracking-tight">Compras</h1>
            <p className="mt-0.5 text-[11.5px] text-zinc-500">Gestão de encomendas, recepções e folgas com fornecedores.</p>
          </div>
          <div className="flex items-center gap-2">
            <button className="h-7 px-2.5 rounded-md border border-zinc-200 text-[11.5px] inline-flex items-center gap-1 text-zinc-700">
              <L name="filter" className="w-3 h-3" />Filtros
              <span className="ml-0.5 rounded-full bg-zinc-900 text-white px-1 text-[9px] font-medium">2</span>
            </button>
            <button className="h-7 px-2.5 rounded-md text-[11.5px] text-white inline-flex items-center gap-1" style={{ background: '#18181B' }}>
              <L name="plus" className="w-3 h-3" />Nova encomenda
            </button>
          </div>
        </div>

        {/* KPI strip */}
        <div className="grid grid-cols-4 gap-2">
          <KpiTile label="Encomendas (página)" value="20" icon="shopping-cart" iconBg="#F0F9FF" iconColor="#0EA5E9"
                   description="6 em aberto" />
          <KpiTile label="Valor total" value="17 256 €" icon="wallet" iconBg="#ECFDF5" iconColor="#10B981"
                   description="s/ IVA" />
          <KpiTile label="Atrasadas" value="2" icon="alert-triangle" iconBg="#FEF2F2" iconColor="#EF4444"
                   description="acção necessária" highlight />
          <KpiTile label="Lead time médio" value="6,4" icon="clock"
                   iconBg="#F4F4F5" iconColor="#52525B" description="dias" />
        </div>

        {/* Table card */}
        <div className="overflow-hidden rounded-xl border border-zinc-200 bg-white shadow-sm flex-1 flex flex-col">
          {/* Search bar inside card */}
          <div className="flex items-center gap-2 border-b border-zinc-100 px-3 py-2">
            <L name="search" className="w-3.5 h-3.5 text-zinc-400" />
            <span className="flex-1 text-[11.5px] text-zinc-400">Procurar por nº ou fornecedor…</span>
            <span className="text-[10px] text-zinc-400 tabular-nums">7 / 247</span>
          </div>

          <table className="w-full text-[11px] flex-1">
            <thead className="bg-zinc-50/60 text-[9.5px] uppercase tracking-widest text-zinc-500">
              <tr>
                <th className="px-3 py-1.5 text-left font-medium">Nº</th>
                <th className="px-3 py-1.5 text-left font-medium">Fornecedor</th>
                <th className="px-3 py-1.5 text-left font-medium">Emissão</th>
                <th className="px-3 py-1.5 text-left font-medium">Prev. entrega</th>
                <th className="px-3 py-1.5 text-left font-medium">Estado</th>
                <th className="px-3 py-1.5 text-right font-medium">Linhas</th>
                <th className="px-3 py-1.5 text-right font-medium">Total</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-zinc-100">
              {rows.map((r, i) => (
                <tr key={i} className="hover:bg-zinc-50/60">
                  <td className="px-3 py-2 font-mono text-[10.5px] text-zinc-700">{r[0]}</td>
                  <td className="px-3 py-2 font-medium text-zinc-900">{r[1]}</td>
                  <td className="px-3 py-2 text-zinc-500">{r[2]}</td>
                  <td className="px-3 py-2 text-zinc-500">{r[3]}</td>
                  <td className="px-3 py-2"><StatusPill tone={r[5]} label={r[4]} /></td>
                  <td className="px-3 py-2 text-right tabular-nums text-zinc-500">{r[6]}</td>
                  <td className="px-3 py-2 text-right tabular-nums font-mono font-semibold">{r[7]}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

// ══════════════════════════════════════════════════════════════════
// SCREEN 3 — Catálogo (Products)
// Mirrors routes/_app/catalog/index.tsx:
//   • Page header + Adicionar produto
//   • 4 KPIs (Total / Activos / Categorias / Lista por defeito)
//   • Search + Mostrar inactivos switch + Category facet chips
//   • Table: SKU · Nome · Categoria · Unidade · Preço base · IVA · Estado
// ══════════════════════════════════════════════════════════════════
function CatalogScreen() {
  const products = [
    ['CIM-3225R-25', 'Cimento Portland II 32,5 R · 25kg',  'Cimentos',           'saco', '4,85 €',  '23%', 'success', 'Activo'],
    ['ARE-FIN-T',    'Areia fina · tonelada',               'Areias e britas',    'ton',  '38,00 €', '23%', 'success', 'Activo'],
    ['TIN-ESM-10L',  'Esmalte sintético branco · 10L',     'Tintas',             'lata', '52,40 €', '23%', 'success', 'Activo'],
    ['SIK-290DC',    'Sikaflex 290 DC · Marítimo',          'Selantes',           'un',   '14,90 €', '23%', 'success', 'Activo'],
    ['PLA-RF13-60',  'Pladur RF 13mm · 1200×2500',          'Pladur e gesso',     'placa','19,30 €', '23%', 'success', 'Activo'],
    ['PER-70-3M',    'Perfis metálicos 70mm · 3m',          'Pladur e gesso',     'un',    '6,80 €', '23%', 'success', 'Activo'],
    ['ADI-PLA-20',   'Aditivo plastificante · 20L',         'Selantes',           'bidão','42,00 €', '23%', 'success', 'Activo'],
    ['PAR-35-500',   'Parafusos 35mm · 500un',              'Ferragens',          'cx',   '12,50 €',  '6%', 'inactive','Inactivo'],
  ];

  return (
    <div className="h-full flex flex-col">
      <div className="flex-1 p-4 overflow-hidden flex flex-col gap-3">
        <div className="flex items-start justify-between">
          <div>
            <h1 className="text-[17px] font-semibold tracking-tight">Catálogo</h1>
            <p className="mt-0.5 text-[11.5px] text-zinc-500">847 produtos · 12 categorias · 3 listas de preço</p>
          </div>
          <button className="h-7 px-2.5 rounded-md text-[11.5px] text-white inline-flex items-center gap-1" style={{ background: '#18181B' }}>
            <L name="plus" className="w-3 h-3" />Novo produto
          </button>
        </div>

        {/* KPIs */}
        <div className="grid grid-cols-4 gap-2">
          <KpiTile label="Total de produtos" value="847" icon="package" />
          <KpiTile label="Produtos activos"  value="812" icon="check-circle-2" iconBg="#ECFDF5" iconColor="#10B981" />
          <KpiTile label="Categorias"        value="12"  icon="folder-tree"   iconBg="#FFFBEB" iconColor="#B45309" />
          <KpiTile label="Lista por defeito" value="Geral 2026" icon="tag"   iconBg="#F0F9FF" iconColor="#0EA5E9" />
        </div>

        {/* Toolbar */}
        <div className="flex items-center gap-3">
          <div className="flex items-center gap-1.5 h-7 w-[200px] rounded-md border border-zinc-200 bg-white px-2">
            <L name="search" className="w-3 h-3 text-zinc-400" />
            <span className="text-[11px] text-zinc-400">Procurar produto…</span>
          </div>
          <div className="flex items-center gap-1.5">
            <span className="h-3.5 w-7 rounded-full bg-zinc-200 relative">
              <span className="absolute left-0.5 top-0.5 h-2.5 w-2.5 rounded-full bg-white shadow"></span>
            </span>
            <span className="text-[11px] text-zinc-700">Mostrar inactivos</span>
          </div>
          <span className="flex-1"></span>
          <div className="flex items-center gap-1">
            {['Tudo (847)', 'Cimentos (42)', 'Areias (18)', 'Tintas (124)', 'Pladur (64)'].map((c, i) => (
              <span key={c} className={'h-6 px-2 rounded-full text-[10.5px] inline-flex items-center ' +
                (i === 0 ? 'bg-zinc-900 text-white' : 'border border-zinc-200 text-zinc-600')}>{c}</span>
            ))}
          </div>
        </div>

        {/* Table */}
        <div className="overflow-hidden rounded-xl border border-zinc-200 bg-white shadow-sm flex-1">
          <table className="w-full text-[11px]">
            <thead className="bg-zinc-50/60 text-[9.5px] uppercase tracking-widest text-zinc-500">
              <tr>
                <th className="px-3 py-1.5 text-left font-medium">SKU</th>
                <th className="px-3 py-1.5 text-left font-medium">Nome</th>
                <th className="px-3 py-1.5 text-left font-medium">Categoria</th>
                <th className="px-3 py-1.5 text-left font-medium">Un.</th>
                <th className="px-3 py-1.5 text-right font-medium">Preço base</th>
                <th className="px-3 py-1.5 text-right font-medium">IVA</th>
                <th className="px-3 py-1.5 text-center font-medium">Estado</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-zinc-100">
              {products.map((p, i) => (
                <tr key={i} className="hover:bg-zinc-50/60">
                  <td className="px-3 py-2 font-mono text-[10.5px] text-zinc-700">{p[0]}</td>
                  <td className="px-3 py-2 font-medium text-zinc-900 truncate max-w-[220px]">{p[1]}</td>
                  <td className="px-3 py-2 text-zinc-500">{p[2]}</td>
                  <td className="px-3 py-2 text-zinc-500">{p[3]}</td>
                  <td className="px-3 py-2 text-right tabular-nums font-mono">{p[4]}</td>
                  <td className="px-3 py-2 text-right tabular-nums text-zinc-500">{p[5]}</td>
                  <td className="px-3 py-2 text-center">
                    <StatusPill tone={p[6] === 'success' ? 'success' : 'neutral'} label={p[7]} />
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

// ══════════════════════════════════════════════════════════════════
// SCREEN 4 — Faturação (Invoicing — AT compliance differentiator)
// Mirrors routes/_app/faturacao/index.tsx:
//   • Page header "Faturação" + subtitle + Filtros · Exportar SAF-T · Nova fatura ▼
//   • 4 KPIs (Emitidas / Recebidas / Em atraso / Prazo médio recebimento)
//   • Search input INSIDE table card header
//   • Columns: Nº · Cliente · Emissão · Vencimento · Estado · Total
//   • Status pills with dot (Rascunho/Emitida/Paga/Vencida/Anulada)
// ══════════════════════════════════════════════════════════════════
function FaturacaoScreen() {
  const invoices = [
    ['FT 2026/0512', 'Construções Faria, Lda.', '14 mai', '14 jun', 'Emitida',  'info',         '8 240 €'],
    ['FT 2026/0511', 'Empreitadas do Centro',    '12 mai', '12 jun', 'Paga',     'success',      '4 980 €'],
    ['FT 2026/0510', 'JNS Construções',          '10 mai', '09 mai', 'Vencida',  'destructive',  '2 415 €'],
    ['FT 2026/0509', 'Materiais Faria, Lda.',    '08 mai', '07 jun', 'Emitida',  'info',         '5 720 €'],
    ['FT 2026/0508', 'Norte Construções',        '06 mai', '06 jun', 'Paga',     'success',     '12 340 €'],
    ['FS 2026/0238', 'Consumidor final',         '05 mai', '—',      'Paga',     'success',        '186 €'],
    ['FT 2026/0507', 'Reabilitar Lisboa, S.A.',  '02 mai', '01 jun', 'Paga',     'success',      '9 120 €'],
    ['FT 2026/0506', 'JNS Construções',          '02 mai', '01 mai', 'Vencida',  'destructive',  '3 280 €'],
  ];

  return (
    <div className="h-full flex flex-col">
      <div className="flex-1 p-4 overflow-hidden flex flex-col gap-3">
        {/* Page header */}
        <div className="flex items-start justify-between">
          <div>
            <h1 className="text-[17px] font-semibold tracking-tight">Faturação</h1>
            <p className="mt-0.5 text-[11.5px] text-zinc-500">Documentos de venda emitidos, comunicados à AT (SAF-T).</p>
          </div>
          <div className="flex items-center gap-2">
            <button className="h-7 px-2.5 rounded-md border border-zinc-200 text-[11.5px] inline-flex items-center gap-1 text-zinc-700">
              <L name="filter" className="w-3 h-3" />Filtros
            </button>
            <button className="h-7 px-2.5 rounded-md border border-zinc-200 text-[11.5px] inline-flex items-center gap-1 text-zinc-700">
              <L name="download" className="w-3 h-3" />Exportar SAF-T
            </button>
            <button className="h-7 px-2.5 rounded-md text-[11.5px] text-white inline-flex items-center gap-1" style={{ background: '#18181B' }}>
              <L name="plus" className="w-3 h-3" />Nova fatura
              <L name="chevron-down" className="w-2.5 h-2.5 opacity-70" />
            </button>
          </div>
        </div>

        {/* KPI strip */}
        <div className="grid grid-cols-4 gap-2">
          <KpiTile label="Emitidas"  value="46 105 €" icon="file-text"      iconBg="#F0F9FF" iconColor="#0EA5E9"
                   description="32 documentos" />
          <KpiTile label="Recebidas" value="38 280 €" icon="wallet"         iconBg="#ECFDF5" iconColor="#10B981"
                   description="83% do emitido" />
          <KpiTile label="Em atraso" value="5 695 €"  icon="alert-triangle" iconBg="#FEF2F2" iconColor="#EF4444"
                   description="2 faturas" highlight />
          <KpiTile label="Prazo médio" value="34 d"   icon="clock"          iconBg="#F4F4F5" iconColor="#52525B"
                   description="DSO" />
        </div>

        {/* Table card */}
        <div className="overflow-hidden rounded-xl border border-zinc-200 bg-white shadow-sm flex-1 flex flex-col">
          <div className="flex items-center gap-2 border-b border-zinc-100 px-3 py-2">
            <L name="search" className="w-3.5 h-3.5 text-zinc-400" />
            <span className="flex-1 text-[11.5px] text-zinc-400">Procurar por nº ou cliente…</span>
            <span className="text-[10px] text-zinc-400 tabular-nums">8 / 32</span>
          </div>

          <table className="w-full text-[11px] flex-1">
            <thead className="bg-zinc-50/60 text-[9.5px] uppercase tracking-widest text-zinc-500">
              <tr>
                <th className="px-3 py-1.5 text-left font-medium">Nº</th>
                <th className="px-3 py-1.5 text-left font-medium">Cliente</th>
                <th className="px-3 py-1.5 text-left font-medium">Emissão</th>
                <th className="px-3 py-1.5 text-left font-medium">Vencimento</th>
                <th className="px-3 py-1.5 text-left font-medium">Estado</th>
                <th className="px-3 py-1.5 text-right font-medium">Total</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-zinc-100">
              {invoices.map((r, i) => (
                <tr key={i} className="hover:bg-zinc-50/60">
                  <td className="px-3 py-2 font-mono text-[10.5px] text-zinc-700">{r[0]}</td>
                  <td className="px-3 py-2 font-medium text-zinc-900">{r[1]}</td>
                  <td className="px-3 py-2 text-zinc-500">{r[2]}</td>
                  <td className="px-3 py-2 text-zinc-500">{r[3]}</td>
                  <td className="px-3 py-2"><StatusPill tone={r[5]} label={r[4]} /></td>
                  <td className="px-3 py-2 text-right tabular-nums font-mono font-semibold">{r[6]}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

// ══════════════════════════════════════════════════════════════════
// SCREEN 6 — Portal B2B (customer-facing)
// Mirrors routes/portal/catalog.tsx + components/layout/portal-shell.tsx:
//   • max-w-1100 header: TenantLogo + tenant name + "Portal B2B" + nav + cart + avatar
//   • Page header: Catálogo + subtitle "Preços especiais para clientes B2B…"
//   • Search input
//   • ProductGrid: aspect-square image area · SKU font-mono · name · price · cart button
// ══════════════════════════════════════════════════════════════════
function PortalScreen() {
  const products = [
    { sku: 'CIM-3225R-25', n: 'Cimento Portland II 32,5 R · 25kg', p: '4,85 €',  s: 'Em stock (340)', ico: 'package' },
    { sku: 'PLA-RF13-60',  n: 'Pladur RF 13mm · 1200×2500',         p: '19,30 €', s: 'Em stock (62)',  ico: 'layers' },
    { sku: 'SIK-290DC',    n: 'Sikaflex 290 DC · Marítimo',          p: '14,90 €', s: 'Crítico (8)',    ico: 'flask-conical' },
    { sku: 'TIN-ESM-10L',  n: 'Esmalte sintético branco · 10L',     p: '52,40 €', s: 'Em stock (24)',  ico: 'paint-bucket' },
    { sku: 'PER-70-3M',    n: 'Perfis metálicos 70mm · 3m',          p:  '6,80 €', s: 'Em stock (180)', ico: 'ruler' },
    { sku: 'ARE-FIN-T',    n: 'Areia fina · tonelada',                p: '38,00 €', s: 'Em stock (12)',  ico: 'mountain' },
    { sku: 'ADI-PLA-20',   n: 'Aditivo plastificante · 20L',          p: '42,00 €', s: 'Em stock (40)',  ico: 'flask-conical' },
    { sku: 'PAR-35-500',   n: 'Parafusos 35mm · 500un',               p: '12,50 €', s: 'Em stock (96)',  ico: 'wrench' },
  ];

  return (
    <div className="h-full flex flex-col bg-zinc-50/30">
      <div className="flex-1 p-4 overflow-hidden">
        {/* Page header */}
        <div className="mb-3 flex items-start justify-between">
          <div>
            <h1 className="text-[17px] font-semibold tracking-tight">Catálogo</h1>
            <p className="mt-0.5 text-[11.5px] text-zinc-500">Preços especiais para clientes B2B. Entrega em 24–48h úteis.</p>
          </div>
          <div className="inline-flex items-center gap-1.5 h-7 px-2.5 rounded-md border border-zinc-200 bg-white text-[11.5px]">
            <L name="shopping-cart" className="w-3 h-3" />Ver carrinho
          </div>
        </div>

        {/* Search */}
        <div className="mb-3 flex items-center gap-1.5 h-7 w-[240px] rounded-md border border-zinc-200 bg-white px-2">
          <L name="search" className="w-3 h-3 text-zinc-400" />
          <span className="text-[11px] text-zinc-400">Procurar produto…</span>
        </div>

        {/* Product grid — 4 columns, aspect-square image area.
            Photos are deterministic-by-SKU via picsum.photos/seed/<sku>; the
            icon sits underneath so it shows during load and degrades cleanly
            if the CDN is unreachable. Real product photos uploaded by the
            tenant replace these in the actual app. */}
        <div className="grid grid-cols-4 gap-2.5">
          {products.map((p) => (
            <div key={p.sku} className="rounded-xl border border-zinc-200 bg-white overflow-hidden shadow-sm">
              <div className="aspect-square bg-zinc-50 border-b border-zinc-100 relative overflow-hidden">
                <div className="absolute inset-0 grid place-items-center text-zinc-300">
                  <L name={p.ico} className="w-7 h-7" style={{ strokeWidth: 1.2 }} />
                </div>
                <img src={`https://picsum.photos/seed/${encodeURIComponent(p.sku)}/240/240`}
                     alt={p.n}
                     loading="lazy"
                     className="absolute inset-0 h-full w-full object-cover" />
              </div>
              <div className="p-2 space-y-0.5">
                <div className="text-[8.5px] font-mono text-zinc-500 tracking-tight">{p.sku}</div>
                <div className="text-[10.5px] font-medium leading-tight line-clamp-2 min-h-[26px]">{p.n}</div>
                <div className="text-[9px] text-zinc-500">{p.s}</div>
                <div className="flex items-center justify-between pt-0.5">
                  <span className="text-[11px] font-semibold">{p.p}</span>
                  <button className="h-5 w-5 rounded grid place-items-center border border-zinc-200 hover:bg-zinc-50">
                    <L name="shopping-cart" className="w-2.5 h-2.5" />
                  </button>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// ══════════════════════════════════════════════════════════════════
// Slideshow controller
// ══════════════════════════════════════════════════════════════════
// One consolidated set of real screens. The faux browser-bar `url` shows the
// brand + section only — never the internal infra domain.
const TOUR_SCREENS = [
  { id: 'dash',    label: 'Painel',             sub: 'Tarefas, obras em curso, recebimentos e alertas — num só ecrã.',        icon: 'layout-dashboard', url: 'ConstructHub · Painel',      shot: 'assets/screenshots/tour-painel.png' },
  { id: 'compras', label: 'Compras',            sub: 'Encomendas a fornecedores com KPIs, filtros e estados auditáveis.',      icon: 'truck',            url: 'ConstructHub · Compras',     shot: 'assets/screenshots/tour-compras.png' },
  { id: 'catalog', label: 'Catálogo',           sub: 'Produtos, categorias e listas de preço — operação completa.',            icon: 'package',          url: 'ConstructHub · Catálogo',    shot: 'assets/screenshots/tour-catalogo.png' },
  { id: 'fatura',  label: 'Faturação',          sub: 'Comunicação directa à AT, SAF-T num clique, 6 tipos de documento.',      icon: 'file-text',        url: 'ConstructHub · Faturação',   shot: 'assets/screenshots/tour-faturacao.png' },
  { id: 'crm',     label: 'CRM · Comercial',    sub: 'Clientes, oportunidades e pipeline comercial ponderado.',                icon: 'users',            url: 'ConstructHub · Clientes',    shot: 'assets/screenshots/gallery-crm.png' },
  { id: 'sched',   label: 'Cronograma',         sub: 'Gantt com caminho crítico (CPM) — paridade Primavera P6.',               icon: 'bar-chart-3',      url: 'ConstructHub · Cronograma',  shot: 'assets/screenshots/gallery-scheduler.png' },
  { id: 'cal',     label: 'Calendários',        sub: 'Calendários de trabalho por obra — semanas, turnos e feriados.',         icon: 'calendar',         url: 'ConstructHub · Calendários', shot: 'assets/screenshots/gallery-calendars.png' },
  { id: 'portal',  label: 'Portal B2B',         sub: 'A loja online dos seus clientes empreiteiros e construtoras.',           icon: 'store',            url: 'Portal B2B · marca do cliente', shot: 'assets/screenshots/tour-portal.png' },
  { id: 'ai',      label: 'Assistente IA',      sub: 'Pergunte em português; analisa obras, faturas e margens, com citações.', icon: 'sparkles',         url: 'ConstructHub · Assistente',  shot: 'assets/screenshots/gallery-ai.png' },
];

const AUTO_ADVANCE_MS = 7000;

function ProductTour() {
  const [active, setActive] = React.useState(0);
  const [paused, setPaused] = React.useState(false);
  const [progress, setProgress] = React.useState(0);
  const [zoom, setZoom] = React.useState(false);
  // Auto-advance + progress
  React.useEffect(() => {
    if (paused) return;
    setProgress(0);
    const tick = setInterval(() => setProgress(p => Math.min(100, p + 100 / (AUTO_ADVANCE_MS / 50))), 50);
    const advance = setTimeout(() => setActive(a => (a + 1) % TOUR_SCREENS.length), AUTO_ADVANCE_MS);
    return () => { clearInterval(tick); clearTimeout(advance); };
  }, [active, paused]);

  // Keyboard nav
  React.useEffect(() => {
    const handler = (e) => {
      if (e.key === 'ArrowLeft')  setActive(a => (a - 1 + TOUR_SCREENS.length) % TOUR_SCREENS.length);
      if (e.key === 'ArrowRight') setActive(a => (a + 1) % TOUR_SCREENS.length);
      if (e.key === 'Escape')     setZoom(false);
    };
    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, []);

  const go = (i) => {
    setActive(i);
    setProgress(0);
  };

  return (
    <section className="border-b border-zinc-100 bg-gradient-to-b from-zinc-50/40 to-white" id="tour">
      <div className="max-w-[1240px] mx-auto px-4 sm:px-6 lg:px-8 py-16 sm:py-20 lg:py-24">
        <div className="flex flex-col gap-6 mb-10 lg:grid lg:grid-cols-12 lg:gap-12 lg:mb-12 lg:items-end">
          <div className="lg:col-span-7">
            <div className="text-[11px] uppercase tracking-[0.16em] text-zinc-500 font-semibold mb-3 flex items-center gap-2">
              <span className="h-1.5 w-1.5 rounded-full" style={{ background: TOUR_INDIGO }}></span>
              Veja por dentro
            </div>
            <h2 className="text-[28px] sm:text-[32px] lg:text-[40px] leading-[1.1] font-semibold tracking-tight">
              Os ecrãs reais.<br/>
              Um ERP completo.
            </h2>
          </div>
          <div className="lg:col-span-5 text-[14px] text-zinc-600 leading-relaxed">
            Estes são os ecrãs do ConstructHub — desenhados para a forma como o sector trabalha, com a densidade certa, atalhos de teclado (<kbd className="font-mono text-[10px] px-1 py-0.5 border border-zinc-200 rounded">⌘K</kbd> para procurar), e o assistente IA a um clique de distância. Carregue numa miniatura para fixar; clique no ecrã para ampliar.
          </div>
        </div>

        <div className="flex flex-col gap-6"
             onMouseEnter={() => setPaused(true)}
             onMouseLeave={() => setPaused(false)}>
          {/* Viewport — full width */}
          <div className="relative">
            <div className="relative h-[440px] sm:h-[520px] lg:h-[600px]">
              {TOUR_SCREENS.map((s, i) => {
                const isActive = i === active;
                const offset = i - active;
                return (
                  <div key={s.id}
                       className="absolute inset-0 transition-all duration-500"
                       style={{
                         opacity: isActive ? 1 : 0,
                         transform: isActive
                           ? 'translateY(0) scale(1)'
                           : `translateY(${offset > 0 ? 20 : -20}px) scale(0.98)`,
                         pointerEvents: isActive ? 'auto' : 'none',
                         zIndex: isActive ? 2 : 1,
                       }}>
                    <BrowserFrame url={s.url}>
                      <img src={s.shot} alt={s.label}
                           onClick={() => setZoom(true)}
                           className="block w-full h-full object-cover object-top cursor-zoom-in" />
                    </BrowserFrame>
                  </div>
                );
              })}
            </div>

            {/* Bottom controls */}
            <div className="mt-5 flex items-center gap-3">
              <button onClick={() => go((active - 1 + TOUR_SCREENS.length) % TOUR_SCREENS.length)}
                      className="h-9 w-9 rounded-md border border-zinc-200 grid place-items-center hover:bg-zinc-50">
                <L name="arrow-left" className="w-3.5 h-3.5" />
              </button>
              <button onClick={() => setPaused(p => !p)}
                      className="h-9 w-9 rounded-md border border-zinc-200 grid place-items-center hover:bg-zinc-50">
                <L name={paused ? 'play' : 'pause'} className="w-3.5 h-3.5" />
              </button>
              <button onClick={() => go((active + 1) % TOUR_SCREENS.length)}
                      className="h-9 w-9 rounded-md border border-zinc-200 grid place-items-center hover:bg-zinc-50">
                <L name="arrow-right" className="w-3.5 h-3.5" />
              </button>
              <div className="flex-1 flex items-center gap-1.5">
                {TOUR_SCREENS.map((_, i) => (
                  <button key={i} onClick={() => go(i)}
                          className="flex-1 h-1 rounded-full overflow-hidden bg-zinc-200">
                    <div className="h-full transition-all"
                         style={{
                           width: i < active ? '100%' : i === active ? `${progress}%` : '0%',
                           background: i <= active ? '#18181B' : 'transparent',
                         }}></div>
                  </button>
                ))}
              </div>
              <span className="text-[11.5px] text-zinc-400 font-mono tabular-nums">
                {String(active + 1).padStart(2, '0')} / {String(TOUR_SCREENS.length).padStart(2, '0')}
              </span>
            </div>
          </div>

          {/* Thumbnail cards — horizontal, under the viewport */}
          <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3">
            {TOUR_SCREENS.map((s, i) => {
              const isActive = i === active;
              return (
                <button key={s.id} onClick={() => go(i)}
                        className={'text-left rounded-xl border p-3 transition-all ' +
                          (isActive ? 'border-zinc-900 bg-white shadow-sm' : 'border-zinc-200 bg-white/60 hover:bg-white hover:border-zinc-300')}>
                  <div className="flex items-center gap-2">
                    <div className={'h-8 w-8 rounded-md grid place-items-center shrink-0 ' + (isActive ? 'text-white' : 'bg-zinc-100 text-zinc-700')}
                         style={isActive ? { background: '#18181B' } : {}}>
                      <L name={s.icon} className="w-4 h-4" />
                    </div>
                    <div className={'text-[12.5px] font-semibold leading-tight min-w-0 truncate ' + (isActive ? 'text-zinc-900' : 'text-zinc-700')}>{s.label}</div>
                    {isActive && <span className="h-1.5 w-1.5 rounded-full animate-pulse shrink-0" style={{ background: TOUR_INDIGO }}></span>}
                  </div>
                  <div className="text-[11px] text-zinc-500 mt-1.5 leading-snug line-clamp-2">{s.sub}</div>
                  <div className="mt-2 h-1 rounded-full bg-zinc-100 overflow-hidden">
                    <div className="h-full transition-all" style={{ width: isActive ? `${progress}%` : '0%', background: isActive ? TOUR_INDIGO : 'transparent' }}></div>
                  </div>
                </button>
              );
            })}
          </div>
        </div>

        <div className="mt-10 flex items-center justify-center gap-3 text-[11.5px] text-zinc-500">
          <span className="inline-flex items-center gap-1.5"><L name="mouse" className="w-3 h-3" />Passe o rato para pausar</span>
          <span className="text-zinc-300">·</span>
          <span className="inline-flex items-center gap-1.5"><kbd className="font-mono text-[10px] px-1.5 py-0.5 border border-zinc-200 rounded">←</kbd><kbd className="font-mono text-[10px] px-1.5 py-0.5 border border-zinc-200 rounded">→</kbd> Navegar</span>
          <span className="text-zinc-300">·</span>
          <span className="inline-flex items-center gap-1.5"><L name="hand" className="w-3 h-3" />Carregue numa miniatura para fixar</span>
        </div>
      </div>

      {zoom && (
        <div onClick={() => setZoom(false)}
             className="fixed inset-0 z-[300] grid place-items-center p-4 sm:p-8" style={{ background: 'rgba(9,9,11,0.92)' }}>
          <img src={TOUR_SCREENS[active].shot} alt={TOUR_SCREENS[active].label}
               className="max-w-full max-h-full rounded-lg shadow-2xl" />
          <button type="button" onClick={() => setZoom(false)} aria-label="Fechar"
                  className="absolute top-4 right-5 h-10 w-10 rounded-full bg-white/10 text-white text-[22px] leading-none grid place-items-center hover:bg-white/20">×</button>
          <div className="absolute bottom-5 left-0 right-0 text-center text-white/80 text-[13px]">{TOUR_SCREENS[active].label}</div>
        </div>
      )}
    </section>
  );
}

Object.assign(window, { ProductTour });
