// Interactive Demo — Desktop (Chrome window) ↔ Mobile (iPhone) toggle.
// No side context panel — the device IS the show.

const IDEMO_NAV = [
{ id: "dashboard", label: "Dashboard", Icon: IconDashboard },
{ id: "clientes", label: "Clientes", Icon: IconUsers },
{ id: "folha", label: "Folha de ponto", Icon: IconClock },
{ id: "obras", label: "Obras", Icon: IconBuilding, sub: "Condomínio das Acácias" },
{ id: "servicos", label: "Serviços", Icon: IconClipboard },
{ id: "equipe", label: "Equipe", Icon: IconTeam },
{ id: "financeiro", label: "Financeiro", Icon: IconWallet },
{ id: "relatorios", label: "Relatórios", Icon: IconReport },
{ id: "config", label: "Configurações", Icon: IconGear }];


const PAGE_URLS = {
  dashboard: "app.bingest.com.br/dashboard",
  clientes: "app.bingest.com.br/clientes",
  folha: "app.bingest.com.br/folha-de-ponto",
  obras: "app.bingest.com.br/obras",
  servicos: "app.bingest.com.br/servicos",
  equipe: "app.bingest.com.br/equipe",
  financeiro: "app.bingest.com.br/financeiro",
  relatorios: "app.bingest.com.br/relatorios",
  config: "app.bingest.com.br/configuracoes"
};

function InteractiveDemo() {
  const [device, setDevice] = React.useState("desktop"); // desktop | mobile
  const [page, setPage] = React.useState("dashboard");
  const [mobileScreen, setMobileScreen] = React.useState("inicio");
  const [toast, setToast] = React.useState(null);
  const [hintActive, setHintActive] = React.useState(true);

  const fireToast = React.useCallback((msg) => {
    setToast({ msg, t: Date.now() });
    setTimeout(() => setToast(null), 3000);
  }, []);

  const goTo = (id) => {
    setPage(id);
    setHintActive(false);
  };

  return (
    <section id="demo" style={{
      paddingTop: 100, paddingBottom: 120,
      position: "relative",
      overflow: "hidden"
    }}>
      {/* Soft ambient backdrop */}
      <div aria-hidden="true" style={{
        position: "absolute", inset: 0,
        background:
        "radial-gradient(circle at 25% 30%, rgba(42,91,255,.10), transparent 50%)," +
        "radial-gradient(circle at 75% 70%, rgba(124,91,216,.06), transparent 55%)",
        pointerEvents: "none"
      }} />
      <div aria-hidden="true" style={{
        position: "absolute", inset: 0,
        backgroundImage:
        "linear-gradient(to right, rgba(255,255,255,.03) 1px, transparent 1px), linear-gradient(to bottom, rgba(255,255,255,.03) 1px, transparent 1px)",
        backgroundSize: "56px 56px",
        maskImage: "radial-gradient(ellipse at 50% 50%, #000 30%, transparent 80%)",
        WebkitMaskImage: "radial-gradient(ellipse at 50% 50%, #000 30%, transparent 80%)",
        pointerEvents: "none"
      }} />

      <div className="container relative">
        {/* Header */}
        <div style={{
          display: "grid", gridTemplateColumns: "1.4fr auto", gap: 24,
          alignItems: "end", marginBottom: 40, flexWrap: "wrap"
        }} className="demo-head">
          <div style={{ maxWidth: 760 }}>
            <div className="t-eyebrow" style={{ marginBottom: 16 }}>Demo ao vivo · clique e navegue</div>
            <h2 className="t-h1" style={{ margin: 0, marginBottom: 14 }}>
              Experimente <span style={{ color: "var(--blue-600)" }}>o sistema de verdade</span>
            </h2>
            <p className="t-lead">Navegue pelo BinGest agora. Veja como sua empresa fica organizada — no computador ou no celular.


            </p>
          </div>

          <div style={{
            display: "inline-flex", alignItems: "center", gap: 10,
            padding: "10px 16px",
            background: "rgba(255,255,255,.05)", color: "#fff",
            border: "1px solid rgba(255,255,255,.10)",
            borderRadius: 999, fontSize: 13, fontWeight: 500,
            backdropFilter: "blur(8px)"
          }}>
            <span style={{
              width: 7, height: 7, borderRadius: 999, background: "var(--green-500)",
              animation: "hotspot-pulse 1.6s ease-out infinite"
            }} />
            Modo demo · dados de exemplo
          </div>
        </div>

        {/* Device toggle */}
        <div style={{
          display: "flex", justifyContent: "center", marginBottom: 36
        }}>
          <div style={{
            display: "inline-flex",
            padding: 6,
            borderRadius: 999,
            background: "rgba(255,255,255,.04)",
            border: "1px solid rgba(255,255,255,.10)",
            backdropFilter: "blur(8px)",
            position: "relative"
          }}>
            <div style={{
              position: "absolute",
              top: 6, bottom: 6,
              left: device === "desktop" ? 6 : "calc(50% + 3px)",
              width: "calc(50% - 9px)",
              background: "var(--blue-600)",
              borderRadius: 999,
              boxShadow: "0 4px 16px rgba(42,91,255,.5)",
              transition: "left .42s cubic-bezier(.5,.1,.3,1)"
            }} />
            {[
            { id: "desktop", l: "Computador", Icon: IconDashboard },
            { id: "mobile", l: "Celular", Icon: IconClock }].
            map((b) =>
            <button key={b.id}
            onClick={() => setDevice(b.id)}
            style={{
              position: "relative", zIndex: 1,
              background: "transparent",
              border: "none",
              padding: "13px 26px",
              fontSize: 14.5,
              fontWeight: device === b.id ? 600 : 500,
              color: device === b.id ? "#fff" : "rgba(255,255,255,.7)",
              display: "inline-flex", alignItems: "center", gap: 9,
              cursor: "pointer",
              transition: "color .25s"
            }}>
                <DeviceIcon kind={b.id} active={device === b.id} />
                {b.l}
              </button>
            )}
          </div>
        </div>

        {/* Device stage */}
        <div style={{
          position: "relative",
          display: "flex",
          justifyContent: "center",
          minHeight: 720
        }}>
          {device === "desktop" ?
          <DesktopStage page={page} goTo={goTo} onAction={fireToast} hintActive={hintActive} toast={toast} /> :
          <MobileStage screen={mobileScreen} setScreen={setMobileScreen} />}
        </div>

        {/* Bottom CTA */}
        <div style={{
          marginTop: 48, display: "flex", justifyContent: "center", flexWrap: "wrap", gap: 14,
          alignItems: "center"
        }}>
          <a href="#precos" className="btn btn-primary">
            Quero esse sistema na minha empresa <IconArrow size={15} />
          </a>
          <span style={{ color: "var(--muted)", fontSize: 14 }}>7 dias grátis 

          </span>
        </div>
      </div>

      <style>{`
        @media (max-width: 800px) {
          .demo-head { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </section>);

}

// ----- Device icons -------------------------------------------------------
function DeviceIcon({ kind, active }) {
  const c = active ? "currentColor" : "currentColor";
  if (kind === "desktop") {
    return (
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
        <rect x="2" y="4" width="20" height="13" rx="1.5" />
        <path d="M2 17h20M9 21h6M12 17v4" />
      </svg>);

  }
  return (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
      <rect x="6" y="2" width="12" height="20" rx="2.5" />
      <path d="M11 18h2" />
    </svg>);

}

// ============================================================================
// Desktop stage — Browser window with full BinGest UI inside
// ============================================================================

function DesktopStage({ page, goTo, onAction, hintActive, toast }) {
  return (
    <div style={{
      width: "100%",
      maxWidth: 1180,
      position: "relative"
    }}>
      <ChromeWindow
        tabs={[{ title: "BinGest · Gestão de Obras", active: true }]}
        activeIndex={0}
        url={PAGE_URLS[page] || "app.bingest.com.br"}
        width={"100%"}
        height={760}>
        <div className="idemo" style={{
          minHeight: 0, height: "100%",
          borderRadius: 0,
          border: "none",
          boxShadow: "none",
          fontSize: 13.5
        }}>
          <aside className="idemo-side">
            <div className="idemo-brand">
              <IconLogo size={26} />
              <span>BinGest</span>
            </div>
            <nav className="idemo-nav">
              {IDEMO_NAV.map((it) =>
              <React.Fragment key={it.id}>
                  <button
                  className={`idemo-nav-item ${page === it.id ? "is-active" : ""}`}
                  onClick={() => goTo(it.id)}>
                    <it.Icon size={16} />
                    <span>{it.label}</span>
                  </button>
                  {it.sub && page === it.id && <div className="idemo-nav-sub">{it.sub}</div>}
                </React.Fragment>
              )}
            </nav>
            <div className="idemo-side-foot">
              <span>v0.1.0</span>
              <span>‹ Recolher</span>
            </div>
          </aside>

          <div className="idemo-main">
            <div className="idemo-top">
              <div className="idemo-crumbs">Pimba Construções</div>
              <div className="idemo-user">
                <span className="idemo-avatar">BG</span>
                <span>teste@bingest.com</span>
                <IconChevronDown size={14} />
              </div>
            </div>

            <div className="idemo-body" style={{ overflow: "auto" }}>
              {page === "dashboard" && <PageDashboard />}
              {page === "clientes" && <PageClientes onAction={onAction} />}
              {page === "folha" && <PageFolha onAction={onAction} />}
              {page === "obras" && <PageObras onAction={onAction} />}
              {page === "servicos" && <PageServicos onAction={onAction} />}
              {page === "equipe" && <PageEquipe onAction={onAction} />}
              {page === "financeiro" && <PageFinanceiro onAction={onAction} />}
              {page === "relatorios" && <PageStub title="Relatórios" body="Exporte DRE, fluxo de caixa, relatório por obra ou cliente em PDF/CSV. Disponível no app real." />}
              {page === "config" && <PageStub title="Configurações" body="Dados da empresa, usuários, perfis de acesso, integrações. Disponível no app real." />}
            </div>

            {hintActive &&
            <div className="idemo-hint" style={{ top: 140, left: -8 }}>
                <div className="idemo-hint-pulse" />
                <div className="idemo-hint-tag">Clique nos menus →</div>
              </div>
            }

            {toast &&
            <div key={toast.t} className="idemo-toast">
                <IconCheck size={14} /> {toast.msg}
              </div>
            }
          </div>
        </div>
      </ChromeWindow>

      {/* Desktop-mode decorative badges */}
      <DeskFloat
        top={80} left={-12}
        text="9 módulos"
        sub="navegáveis"
        color="var(--blue-600)"
        icon={<IconDashboard size={14} />}
        delay={0} />
      
      <DeskFloat
        bottom={120} right={-14}
        text="DRE"
        sub="auditável"
        color="var(--green-600)"
        icon={<IconReport size={14} />}
        delay={1.4} />
      
    </div>);

}

function PageStub({ title, body }) {
  return (
    <div className="idemo-page" style={{ display: "grid", placeItems: "center", minHeight: 400 }}>
      <div style={{ textAlign: "center", maxWidth: 420 }}>
        <div style={{
          width: 56, height: 56, borderRadius: 14,
          background: "#E9F0FE", color: "#2A5BFF",
          display: "grid", placeItems: "center", margin: "0 auto 18px"
        }}>
          <IconReport size={26} />
        </div>
        <h2 className="idemo-h1" style={{ marginBottom: 10 }}>{title}</h2>
        <div className="idemo-h1-sub">{body}</div>
      </div>
    </div>);

}

// ============================================================================
// Mobile stage — iPhone centered, with decorative context around
// ============================================================================

const MOBILE_SCREEN_LABELS = {
  inicio: "Resumo da empresa, DRE e atividade ao vivo",
  obras: "Acompanhe cada obra com margem e progresso",
  ponto: "Mestre registra presença em segundos",
  fin: "Recebimentos, despesas e equipe num só lugar"
};

function MobileStage({ screen, setScreen }) {
  return (
    <div style={{
      display: "grid",
      gridTemplateColumns: "1fr auto 1fr",
      alignItems: "center",
      gap: 36,
      width: "100%",
      maxWidth: 1180
    }} className="mobile-stage-grid">
      {/* Left context */}
      <div style={{ justifySelf: "end", maxWidth: 320 }} className="mobile-side mobile-side-left">
        <SideBlurb
          align="right"
          label="Para o mestre de obra"
          title="No bolso, no canteiro"
          body="Acesso completo via celular. Lança diária na hora, vê obra atribuída, sincroniza com o sistema da empresa em segundos." />
        
      </div>

      {/* Phone */}
      <div style={{ position: "relative" }}>
        <IOSDevice width={372} height={760}>
          <BingestMobile screen={screen} onNav={setScreen} />
        </IOSDevice>

        {/* Pulse label below pointing at bottom nav */}
        <div style={{
          position: "absolute",
          bottom: -56, left: "50%", transform: "translateX(-50%)",
          display: "inline-flex", alignItems: "center", gap: 8,
          padding: "8px 14px", borderRadius: 999,
          background: "var(--ink)", color: "#fff",
          fontSize: 12, fontWeight: 600,
          boxShadow: "0 8px 20px -8px rgba(0,0,0,.3)",
          whiteSpace: "nowrap"
        }}>
          <span style={{
            width: 6, height: 6, borderRadius: 999, background: "var(--green-500)",
            animation: "hotspot-pulse 1.6s ease-out infinite"
          }} />
          Toque nas abas para navegar
        </div>
      </div>

      {/* Right context — current screen explainer */}
      <div style={{ maxWidth: 320 }} className="mobile-side mobile-side-right">
        <div key={screen} style={{ animation: "fade-up .4s ease both" }}>
          <div className="t-eyebrow" style={{ marginBottom: 12 }}>
            Você está em
          </div>
          <h3 style={{ margin: 0, marginBottom: 10, fontSize: 26, fontWeight: 600, letterSpacing: "-0.02em" }}>
            {{ inicio: "Início", obras: "Obras", ponto: "Folha de ponto", fin: "Financeiro" }[screen]}
          </h3>
          <p style={{ margin: 0, color: "var(--muted)", fontSize: 15, lineHeight: 1.5 }}>
            {MOBILE_SCREEN_LABELS[screen]}
          </p>

          <div style={{
            marginTop: 22,
            padding: "12px 14px",
            borderRadius: 12,
            background: "rgba(255,255,255,.04)",
            border: "1px solid rgba(255,255,255,.10)",
            fontSize: 13, color: "rgba(255,255,255,.85)"
          }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 6 }}>
              <span style={{ width: 22, height: 22, borderRadius: 999, background: "rgba(42,91,255,.2)", color: "#7DA7FF", display: "grid", placeItems: "center" }}>
                <IconBolt size={11} />
              </span>
              <span style={{ fontWeight: 600, color: "#fff" }}>Tente isto:</span>
            </div>
            <span style={{ color: "rgba(255,255,255,.65)" }}>
              {{
                inicio: "Repare nos KPIs ticando — eles atualizam em tempo real conforme novos lançamentos.",
                obras: "Cada obra mostra progresso, margem e receita. No app real, clique para ver detalhes da unidade.",
                ponto: "O check-in funciona offline no canteiro. Sincroniza assim que pegar sinal.",
                fin: "Recebido/Saídas/A receber numa olhada só. Toque em qualquer atalho para o detalhe."
              }[screen]}
            </span>
          </div>
        </div>
      </div>

      <style>{`
        @media (max-width: 1080px) {
          .mobile-stage-grid {
            grid-template-columns: 1fr !important;
            justify-items: center !important;
          }
          .mobile-side { max-width: 480px !important; justify-self: stretch !important; text-align: center; }
          .mobile-side-left { order: 2; }
          .mobile-side-right { order: 3; }
        }
      `}</style>
    </div>);

}

function SideBlurb({ align = "left", label, title, body }) {
  return (
    <div style={{ textAlign: align === "right" ? "right" : "left" }}>
      <div className="t-eyebrow" style={{ marginBottom: 12 }}>{label}</div>
      <h3 style={{
        margin: 0, marginBottom: 10,
        fontSize: 26, fontWeight: 600, letterSpacing: "-0.02em"
      }}>{title}</h3>
      <p style={{ margin: 0, color: "var(--muted)", fontSize: 15, lineHeight: 1.5 }}>
        {body}
      </p>
    </div>);

}

// ----- Decorative floats around the desktop browser -----------------------
function DeskFloat({ top, bottom, left, right, text, sub, color, icon, delay = 0 }) {
  return (
    <div style={{
      position: "absolute",
      top, bottom, left, right,
      background: "#fff",
      border: "1px solid var(--border)",
      borderRadius: 14,
      padding: "10px 14px",
      display: "flex", alignItems: "center", gap: 10,
      boxShadow: "var(--shadow-pop)",
      zIndex: 5,
      animation: `float-y 4.4s ease-in-out infinite`,
      animationDelay: `${delay}s`
    }}>
      <span style={{
        width: 30, height: 30, borderRadius: 10,
        background: color, color: "#fff",
        display: "grid", placeItems: "center",
        flex: "0 0 30px"
      }}>{icon}</span>
      <div>
        <div className="mono tabular" style={{ fontSize: 14, fontWeight: 600, letterSpacing: "-0.02em", lineHeight: 1.1 }}>{text}</div>
        <div style={{ fontSize: 11, color: "var(--muted)", marginTop: 2 }}>{sub}</div>
      </div>
    </div>);

}

window.InteractiveDemo = InteractiveDemo;