const demoTabs = [
  { id: 'dashboard', label: 'Dashboard', sheet: 'WEB-01', path: '/', active: ['dashboard'] },
  { id: 'comercial', label: 'Clientes e propostas', sheet: 'WEB-02', path: '/clients', active: ['clients', 'proposals', 'contracts'] },
  { id: 'financeiro', label: 'Financeiro', sheet: 'WEB-03', path: '/financial/cash-flow', active: ['financial'] },
  { id: 'operacao', label: 'Tarefas e anexos', sheet: 'WEB-04', path: '/tasks', active: ['tasks', 'attachments'] },
  { id: 'gestao', label: 'Relatórios e admin', sheet: 'WEB-05', path: '/reports', active: ['reports', 'settings', 'appearance'] },
];

const demoSidebar = [
  { id: 'dashboard', label: 'Dashboard', route: '/' },
  { id: 'clients', label: 'Clientes', route: '/clients' },
  { id: 'proposals', label: 'Propostas', route: '/proposals' },
  { id: 'contracts', label: 'Contratos', route: '/contracts' },
  { id: 'financial', label: 'Financeiro', route: '/financial/cash-flow' },
  { id: 'tasks', label: 'Tarefas', route: '/tasks' },
  { id: 'attachments', label: 'Anexos', route: '/attachments' },
  { id: 'reports', label: 'Relatórios', route: '/reports' },
  { id: 'appearance', label: 'Aparência', route: '/appearance' },
  { id: 'settings', label: 'Admin', route: '/settings' },
];

const money = (value) => `R$ ${value.toLocaleString('pt-BR')}`;

const Demo = () => {
  const [tab, setTab] = React.useState('dashboard');
  const [ref, inView] = useReveal({ threshold: 0.1 });
  const current = demoTabs.find((item) => item.id === tab) || demoTabs[0];

  return (
    <section id="demo" className="relative py-32 md:py-48 border-t" style={{ borderColor: 'var(--rule)', background: 'var(--bg-deep)' }} data-screen-label="03 Demo">
      <div className="max-w-[1400px] mx-auto px-6 md:px-10">
        <div className="grid grid-cols-12 gap-x-6">
          <div className="col-span-12 md:col-span-8">
            <SectionHeader
              index="03"
              label="Demo / Módulos reais"
              title={<>Veja o <em className="italic font-serif" style={{ color: 'var(--sepia)' }}>sistema</em> por dentro.</>}
              kicker="A prévia abaixo foi montada a partir das rotas e módulos ativos: clientes, propostas, contratos, financeiro, tarefas, anexos, relatórios, aparência e administração."
            />
          </div>
        </div>

        <div ref={ref} className="mt-20">
          <div className="flex flex-wrap items-end justify-between mb-4 gap-4">
            <div className="flex flex-wrap gap-px" style={{ background: 'var(--rule-strong)' }}>
              {demoTabs.map((item) => (
                <button
                  key={item.id}
                  onClick={() => setTab(item.id)}
                  className="px-5 py-3 font-mono text-[11px] uppercase tracking-wider2 transition-all"
                  style={{
                    background: tab === item.id ? 'var(--ink)' : 'var(--bg)',
                    color: tab === item.id ? 'var(--bg)' : 'var(--ash)',
                  }}
                >
                  / {item.label}
                </button>
              ))}
            </div>
            <DimLabel>Sheet {current.sheet} / ROTA {current.path}</DimLabel>
          </div>

          <div className="relative corner-ticks" style={{ background: 'var(--bg)', border: '1px solid var(--rule-strong)' }}>
            <span className="tl"></span><span className="tr"></span>
            <DemoWindow tab={tab} inView={inView} />
          </div>

          <div className="mt-4 flex flex-wrap justify-between gap-2 font-mono text-[10px] uppercase tracking-wider2" style={{ color: 'var(--stone)' }}>
            <span>/ Simulação baseada nos módulos implementados</span>
            <span>/ Sem telas fictícias de timesheet ou equipe</span>
            <span>/ Rotas web reais do ArchPlan</span>
          </div>
        </div>
      </div>
    </section>
  );
};

const DemoWindow = ({ tab, inView }) => {
  const current = demoTabs.find((item) => item.id === tab) || demoTabs[0];

  return (
    <div className="relative">
      <div className="flex items-center justify-between gap-4 px-5 py-3 border-b" style={{ borderColor: 'var(--rule)' }}>
        <div className="flex items-center gap-3 min-w-0">
          <div className="flex gap-1.5 shrink-0">
            <div className="w-2.5 h-2.5 rounded-full" style={{ background: 'var(--mist)' }}></div>
            <div className="w-2.5 h-2.5 rounded-full" style={{ background: 'var(--mist)' }}></div>
            <div className="w-2.5 h-2.5 rounded-full" style={{ background: 'var(--mist)' }}></div>
          </div>
          <span className="font-mono text-[10px] uppercase tracking-wider2 ml-3 truncate" style={{ color: 'var(--stone)' }}>archplan.app{current.path}</span>
        </div>
        <span className="hidden sm:inline font-mono text-[10px] uppercase tracking-wider2" style={{ color: 'var(--stone)' }}>WORKSPACE / ADMIN</span>
      </div>

      <div className="grid grid-cols-12 min-h-[640px]">
        <aside className="hidden lg:block col-span-2 border-r p-4" style={{ borderColor: 'var(--rule)' }}>
          {demoSidebar.map((item) => {
            const active = current.active.includes(item.id);
            return (
              <div
                key={item.id}
                className="px-2 py-2 font-mono text-[10px] uppercase tracking-wider2 flex items-start gap-2"
                style={{ color: active ? 'var(--ink)' : 'var(--stone)', background: active ? 'var(--bg-deep)' : 'transparent' }}
              >
                <span className="mt-1.5 w-1 h-1 rounded-full shrink-0" style={{ background: active ? 'var(--sepia)' : 'transparent' }}></span>
                <span>
                  <span className="block">{item.label}</span>
                  <span className="block mt-0.5 text-[8px]" style={{ color: 'var(--stone)' }}>{item.route}</span>
                </span>
              </div>
            );
          })}
        </aside>

        <div className="col-span-12 lg:col-span-10 p-5 md:p-8 overflow-hidden">
          {tab === 'dashboard' && <ScreenDashboard inView={inView} />}
          {tab === 'comercial' && <ScreenComercial inView={inView} />}
          {tab === 'financeiro' && <ScreenFinanceiro inView={inView} />}
          {tab === 'operacao' && <ScreenOperacao inView={inView} />}
          {tab === 'gestao' && <ScreenGestao inView={inView} />}
        </div>
      </div>
    </div>
  );
};

const RouteChips = ({ routes }) => (
  <div className="flex flex-wrap gap-2">
    {routes.map((route) => (
      <span key={route} className="font-mono text-[10px] uppercase tracking-wider2 px-2 py-1" style={{ border: '1px solid var(--rule)', color: 'var(--stone)' }}>
        {route}
      </span>
    ))}
  </div>
);

const StatCard = ({ label, value, caption, delay = 0 }) => (
  <div
    className="p-5"
    style={{
      background: 'var(--bg)',
      opacity: 1,
      transition: `opacity 500ms ${delay}ms, transform 500ms ${delay}ms`,
    }}
  >
    <DimLabel>{label}</DimLabel>
    <div className="mt-2 font-serif text-2xl md:text-3xl tracking-tightest">{value}</div>
    <div className="font-mono text-[10px] mt-2 uppercase tracking-wider2" style={{ color: 'var(--stone)' }}>{caption}</div>
  </div>
);

const ProgressLine = ({ value, delay = 0, tone = 'ink' }) => (
  <div className="h-1 relative" style={{ background: 'var(--rule)' }}>
    <div
      className="absolute left-0 top-0 h-1 transition-all duration-1500 ease-out"
      style={{ width: `${value}%`, background: tone === 'sepia' ? 'var(--sepia)' : 'var(--ink)', transitionDelay: `${delay}ms` }}
    ></div>
  </div>
);

const ScreenDashboard = ({ inView }) => {
  const months = ['JAN', 'FEV', 'MAR', 'ABR', 'MAI', 'JUN'];
  const entries = [42, 58, 71, 66, 88, 94];
  const expenses = [32, 38, 47, 44, 53, 61];

  return (
    <div>
      <div className="flex flex-wrap items-baseline justify-between gap-3 mb-2">
        <DimLabel>DASHBOARD / CENTRO DE COMANDO</DimLabel>
        <RouteChips routes={['/', '/financial/receivables', '/proposals/new']} />
      </div>
      <h3 className="font-serif text-3xl tracking-tightest mb-1">Leitura operacional do escritório</h3>
      <p className="text-sm mb-8" style={{ color: 'var(--ash)' }}>A mesma visão consolida caixa, vencimentos, propostas, clientes ativos e tarefas pendentes.</p>

      <div className="grid grid-cols-2 xl:grid-cols-4 gap-px mb-8" style={{ background: 'var(--rule-strong)' }}>
        <StatCard label="Entradas do mês" value={<Counter to={186400} prefix="R$ " />} caption="Recebido no período" />
        <StatCard label="Saídas do mês" value={<Counter to={72400} prefix="R$ " />} caption="Pago no período" delay={80} />
        <StatCard label="Saldo atual" value={<Counter to={114000} prefix="R$ " />} caption="Entradas menos saídas" delay={160} />
        <StatCard label="A receber" value={<Counter to={238900} prefix="R$ " />} caption="Pendentes e vencidas" delay={240} />
      </div>

      <div className="grid lg:grid-cols-[1.2fr_0.8fr] gap-8">
        <div>
          <div className="flex items-center justify-between mb-3">
            <DimLabel>Entradas x saídas</DimLabel>
            <DimLabel>R$ MIL</DimLabel>
          </div>
          <div className="relative h-56 border-b" style={{ borderColor: 'var(--rule-strong)' }}>
            <div className="absolute inset-0 flex items-end justify-between gap-2 px-2">
              {months.map((month, index) => (
                <div key={month} className="flex-1 flex items-end gap-1">
                  <div
                    className="flex-1 transition-all duration-1000 ease-out"
                    style={{ height: inView ? `${entries[index]}%` : '0%', background: 'var(--ink)', transitionDelay: `${index * 70}ms` }}
                  ></div>
                  <div
                    className="flex-1 transition-all duration-1000 ease-out"
                    style={{ height: inView ? `${expenses[index]}%` : '0%', background: 'var(--sepia)', transitionDelay: `${index * 70 + 30}ms` }}
                  ></div>
                </div>
              ))}
            </div>
          </div>
          <div className="grid grid-cols-6 mt-2">
            {months.map((month) => <span key={month} className="font-mono text-[9px]" style={{ color: 'var(--stone)' }}>{month}</span>)}
          </div>
        </div>

        <div className="space-y-px" style={{ background: 'var(--rule)' }}>
          {[
            ['Despesas fixas', money(18400), '/financial/fixed-expenses'],
            ['Parcelas vencidas', '3', '/contracts'],
            ['Clientes ativos', '42', '/clients'],
            ['Tarefas pendentes', '18', '/tasks'],
          ].map(([label, value, route], index) => (
            <div key={label} className="p-4 flex items-center justify-between gap-4" style={{ background: 'var(--bg)' }}>
              <div>
                <div className="font-serif text-lg tracking-tight">{label}</div>
                <div className="font-mono text-[10px] mt-1 uppercase tracking-wider2" style={{ color: 'var(--stone)' }}>{route}</div>
              </div>
              <div className="font-serif text-2xl tracking-tightest">{value}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

const ScreenComercial = ({ inView }) => {
  const rows = [
    { client: 'Studio Almeida', route: '/clients', item: 'Histórico e contatos', value: '12 interações', status: 'ativo' },
    { client: 'Loja Aurora', route: '/proposals', item: 'Proposta comercial', value: money(48200), status: 'enviada' },
    { client: 'Grupo Horizonte', route: '/contracts', item: 'Contrato e parcelas', value: money(186000), status: 'assinado' },
    { client: 'Residencial Norte', route: '/propostas', item: 'PDF de proposta', value: 'versão 3', status: 'revisão' },
  ];

  return (
    <div>
      <div className="flex flex-wrap items-baseline justify-between gap-3 mb-2">
        <DimLabel>COMERCIAL / CLIENTES / PROPOSTAS / CONTRATOS</DimLabel>
        <RouteChips routes={['/clients', '/proposals', '/propostas', '/contracts']} />
      </div>
      <h3 className="font-serif text-3xl tracking-tightest mb-1">Do relacionamento ao contrato</h3>
      <p className="text-sm mb-8" style={{ color: 'var(--ash)' }}>A demo mostra as telas reais de cadastro de clientes, registro de contatos, propostas com PDF e contratos com parcelas.</p>

      <div className="grid lg:grid-cols-[0.8fr_1.2fr] gap-8">
        <div className="space-y-px" style={{ background: 'var(--rule-strong)' }}>
          <StatCard label="Clientes ativos" value="42" caption="Cadastro e histórico" />
          <StatCard label="Propostas abertas" value="9" caption="Edição, envio e PDF" delay={90} />
          <StatCard label="Contratos vigentes" value="17" caption="Parcelas e recebimento" delay={180} />
        </div>

        <div>
          <div className="grid grid-cols-12 gap-px font-mono text-[10px] uppercase tracking-wider2 px-3 py-2" style={{ background: 'var(--bg-deep)', color: 'var(--stone)' }}>
            <div className="col-span-3">Cliente</div>
            <div className="col-span-3">Modulo</div>
            <div className="col-span-2">Rota</div>
            <div className="col-span-2 text-right">Valor</div>
            <div className="col-span-2 text-right">Status</div>
          </div>
          {rows.map((row, index) => (
            <div
              key={row.client}
              className="grid grid-cols-12 gap-px text-sm px-3 py-4 border-b items-center"
              style={{
                borderColor: 'var(--rule)',
                opacity: inView ? 1 : 0,
                transform: inView ? 'translateX(0)' : 'translateX(18px)',
                transition: `opacity 600ms ${index * 90}ms, transform 600ms ${index * 90}ms`,
              }}
            >
              <div className="col-span-3 font-serif text-base tracking-tight">{row.client}</div>
              <div className="col-span-3 text-xs" style={{ color: 'var(--ash)' }}>{row.item}</div>
              <div className="col-span-2 font-mono text-[10px]" style={{ color: 'var(--stone)' }}>{row.route}</div>
              <div className="col-span-2 text-right font-mono text-xs ticker">{row.value}</div>
              <div className="col-span-2 text-right">
                <span className="font-mono text-[10px] uppercase tracking-wider2 px-2 py-1" style={{ border: '1px solid var(--rule)', color: 'var(--ash)' }}>{row.status}</span>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

const ScreenFinanceiro = ({ inView }) => {
  const items = [
    { name: 'Recebíveis', route: '/financial/receivables', amount: 238900, pct: 78, tone: 'ink' },
    { name: 'Contas a pagar', route: '/financial/payables', amount: 86400, pct: 44, tone: 'sepia' },
    { name: 'Entradas', route: '/financial/entries', amount: 186400, pct: 64, tone: 'ink' },
    { name: 'Saídas', route: '/financial/expenses', amount: 72400, pct: 35, tone: 'sepia' },
    { name: 'Despesas fixas', route: '/financial/fixed-expenses', amount: 18400, pct: 18, tone: 'sepia' },
  ];

  return (
    <div>
      <div className="flex flex-wrap items-baseline justify-between gap-3 mb-2">
        <DimLabel>FINANCEIRO / CAIXA / CONTAS</DimLabel>
        <RouteChips routes={['/financial/cash-flow', '/financial/receivables', '/financial/payables']} />
      </div>
      <h3 className="font-serif text-3xl tracking-tightest mb-1">Financeiro separado por operação real</h3>
      <p className="text-sm mb-8" style={{ color: 'var(--ash)' }}>Recebíveis, contas a pagar, entradas, saídas, despesas fixas e fluxo de caixa usam rotas próprias no sistema.</p>

      <div className="grid grid-cols-2 xl:grid-cols-4 gap-px mb-8" style={{ background: 'var(--rule-strong)' }}>
        <StatCard label="A receber" value={money(238900)} caption="/financial/receivables" />
        <StatCard label="A pagar" value={money(86400)} caption="/financial/payables" delay={80} />
        <StatCard label="Saldo previsto" value={money(152500)} caption="/financial/cash-flow" delay={160} />
        <StatCard label="Vencidos" value="3 parcelas" caption="/contracts" delay={240} />
      </div>

      <div className="space-y-4">
        {items.map((item, index) => (
          <div
            key={item.route}
            className="grid grid-cols-12 gap-4 items-center"
            style={{
              opacity: inView ? 1 : 0,
              transform: inView ? 'translateY(0)' : 'translateY(12px)',
              transition: `opacity 600ms ${index * 80}ms, transform 600ms ${index * 80}ms`,
            }}
          >
            <div className="col-span-12 md:col-span-3">
              <div className="font-serif text-lg tracking-tight">{item.name}</div>
              <div className="font-mono text-[10px] mt-1 uppercase tracking-wider2" style={{ color: 'var(--stone)' }}>{item.route}</div>
            </div>
            <div className="col-span-8 md:col-span-7">
              <ProgressLine value={inView ? item.pct : 0} delay={index * 120} tone={item.tone} />
            </div>
            <div className="col-span-4 md:col-span-2 text-right font-serif text-xl tracking-tightest">{money(item.amount)}</div>
          </div>
        ))}
      </div>
    </div>
  );
};

const ScreenOperacao = ({ inView }) => {
  const tasks = [
    { name: 'Revisar proposta comercial', owner: 'César', status: 'pendente', priority: 78 },
    { name: 'Cobrar parcela vencida', owner: 'Financeiro', status: 'urgente', priority: 92 },
    { name: 'Anexar contrato assinado', owner: 'Admin', status: 'em aberto', priority: 64 },
    { name: 'Atualizar contato do cliente', owner: 'Comercial', status: 'hoje', priority: 48 },
  ];

  return (
    <div>
      <div className="flex flex-wrap items-baseline justify-between gap-3 mb-2">
        <DimLabel>OPERAÇÃO / TAREFAS / ANEXOS</DimLabel>
        <RouteChips routes={['/tasks', '/tasks/new', '/attachments']} />
      </div>
      <h3 className="font-serif text-3xl tracking-tightest mb-1">Rotina operacional do escritório</h3>
      <p className="text-sm mb-8" style={{ color: 'var(--ash)' }}>A operação aparece como lista de tarefas, responsáveis, prioridades e anexos vinculados às entidades do sistema.</p>

      <div className="grid lg:grid-cols-[1.15fr_0.85fr] gap-8">
        <div className="space-y-px" style={{ background: 'var(--rule)' }}>
          {tasks.map((task, index) => (
            <div
              key={task.name}
              className="grid grid-cols-12 gap-4 px-5 py-5 items-center"
              style={{
                background: 'var(--bg)',
                opacity: inView ? 1 : 0,
                transform: inView ? 'translateY(0)' : 'translateY(12px)',
                transition: `opacity 600ms ${index * 80}ms, transform 600ms ${index * 80}ms`,
              }}
            >
              <div className="col-span-5 font-serif text-lg tracking-tight">{task.name}</div>
              <div className="col-span-2 font-mono text-[10px] uppercase tracking-wider2" style={{ color: 'var(--stone)' }}>{task.owner}</div>
              <div className="col-span-3">
                <ProgressLine value={inView ? task.priority : 0} delay={index * 100} tone={task.priority > 80 ? 'sepia' : 'ink'} />
              </div>
              <div className="col-span-2 text-right font-mono text-[10px] uppercase tracking-wider2">{task.status}</div>
            </div>
          ))}
        </div>

        <div className="p-6" style={{ border: '1px solid var(--rule-strong)', background: 'var(--bg-deep)' }}>
          <DimLabel>Anexos por entidade</DimLabel>
          <h4 className="font-serif text-2xl tracking-tightest mt-2 mb-5">Documentos operacionais</h4>
          {[
            ['Contrato assinado', '/attachments/download'],
            ['PDF de proposta', '/proposals/{id}/pdf'],
            ['Comprovante financeiro', '/financial/entries'],
            ['Histórico de cliente', '/clients/{id}'],
          ].map(([label, route], index) => (
            <div
              key={label}
              className="flex items-center justify-between gap-4 py-4 border-b"
              style={{
                borderColor: 'var(--rule)',
                opacity: inView ? 1 : 0,
                transition: `opacity 600ms ${index * 90}ms`,
              }}
            >
              <span className="font-serif text-lg tracking-tight">{label}</span>
              <span className="font-mono text-[10px] uppercase tracking-wider2" style={{ color: 'var(--stone)' }}>{route}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

const ScreenGestao = ({ inView }) => {
  const rows = [
    { module: 'Relatórios', route: '/reports', action: 'Exportação CSV e PDF', state: '3 relatórios' },
    { module: 'Admin', route: '/settings', action: 'Usuários, papéis e permissões', state: 'RBAC' },
    { module: 'Aparência', route: '/appearance', action: 'Tema, layout e densidade', state: 'local' },
    { module: 'Histórico', route: '/system-logs', action: 'Auditoria das ações do sistema', state: 'ativo' },
    { module: 'Assinatura', route: '/assinatura/planos', action: 'Escolha e ativação de plano', state: 'ativo' },
  ];

  return (
    <div>
      <div className="flex flex-wrap items-baseline justify-between gap-3 mb-2">
        <DimLabel>GESTÃO / RELATÓRIOS / ADMIN</DimLabel>
        <RouteChips routes={['/reports', '/settings', '/appearance', '/system-logs']} />
      </div>
      <h3 className="font-serif text-3xl tracking-tightest mb-1">Camada administrativa e operacional</h3>
      <p className="text-sm mb-8" style={{ color: 'var(--ash)' }}>A landing também mostra gestão de relatórios, usuários, permissões, aparência, histórico e assinatura.</p>

      <div className="grid lg:grid-cols-[1.1fr_0.9fr] gap-8">
        <div className="space-y-px" style={{ background: 'var(--rule)' }}>
          {rows.map((row, index) => (
            <div
              key={row.route}
              className="grid grid-cols-12 gap-4 px-5 py-5 items-center"
              style={{
                background: 'var(--bg)',
                opacity: inView ? 1 : 0,
                transform: inView ? 'translateY(0)' : 'translateY(12px)',
                transition: `opacity 600ms ${index * 70}ms, transform 600ms ${index * 70}ms`,
              }}
            >
              <div className="col-span-3 font-serif text-lg tracking-tight">{row.module}</div>
              <div className="col-span-3 font-mono text-[10px] uppercase tracking-wider2" style={{ color: 'var(--stone)' }}>{row.route}</div>
              <div className="col-span-4 text-xs" style={{ color: 'var(--ash)' }}>{row.action}</div>
              <div className="col-span-2 text-right font-mono text-[10px] uppercase tracking-wider2">{row.state}</div>
            </div>
          ))}
        </div>

        <div className="p-6" style={{ border: '1px solid var(--rule-strong)', background: 'var(--bg-deep)' }}>
          <DimLabel>Permissões reais</DimLabel>
          <h4 className="font-serif text-2xl tracking-tightest mt-2 mb-5">Acesso por papel</h4>
          {[
            ['dashboard', 100],
            ['clients:read', 92],
            ['financial:read', 84],
            ['reports:read', 70],
            ['settings', 42],
          ].map(([permission, value], index) => (
            <div key={permission} className="mb-5">
              <div className="flex justify-between gap-3 mb-2 font-mono text-[10px] uppercase tracking-wider2">
                <span>{permission}</span>
                <span style={{ color: 'var(--stone)' }}>{value}%</span>
              </div>
              <ProgressLine value={inView ? value : 0} delay={index * 100} tone={index < 2 ? 'ink' : 'sepia'} />
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

window.Demo = Demo;
