/* global React */
const { useState, useEffect, useRef, useMemo } = React;

// ---------- Lucide icon helper ----------
function Icon({ name, size = 18, className = "", strokeWidth = 1.75 }) {
  const ref = useRef(null);
  useEffect(() => {
    if (window.lucide && ref.current) {
      ref.current.innerHTML = "";
      const el = document.createElement("i");
      el.setAttribute("data-lucide", name);
      el.setAttribute("width", String(size));
      el.setAttribute("height", String(size));
      el.setAttribute("stroke-width", String(strokeWidth));
      ref.current.appendChild(el);
      window.lucide.createIcons({ attrs: { width: size, height: size, "stroke-width": strokeWidth } });
    }
  }, [name, size, strokeWidth]);
  return <span ref={ref} className={`inline-flex items-center justify-center ${className}`} style={{ width: size, height: size }} />;
}

// ---------- Brand mark used in nav + modals ----------
function LogoMark({ size = 28 }) {
  return (
    <img src="assets/suntech-logo-v2.png" alt="SUN TECH" style={{ height: size, width: 'auto' }} draggable={false} />);

}

// ---------- Decorative orbital background ----------
function OrbitalBackdrop() {
  return (
    <div className="pointer-events-none absolute inset-0 overflow-hidden">
      {/* center orbit ring */}
      <div className="absolute left-1/2 top-[42%] -translate-x-1/2 -translate-y-1/2 spin-slow">
        <div className="ring-orbit" style={{ width: 1400, height: 1400, transform: 'rotate(-18deg)' }}></div>
      </div>
      <div className="absolute left-1/2 top-[42%] -translate-x-1/2 -translate-y-1/2 spin-slower">
        <div className="ring-orbit" style={{ width: 1900, height: 1900, borderColor: 'rgba(217,225,236,.06)', transform: 'rotate(-18deg)' }}></div>
      </div>
      {/* cyan glow (sun replaced by tech aura) */}
      <div className="absolute -right-32 top-16 w-[480px] h-[480px] rounded-full"
      style={{ background: 'radial-gradient(circle at 50% 50%, rgba(26,182,240,.32), rgba(26,182,240,0) 70%)' }} />
      {/* signature star — echoes the logo */}
      <div className="absolute right-[18%] top-[18%] pulse-soft">
        <div className="w-1.5 h-1.5 rounded-full bg-cy-200 shadow-[0_0_22px_5px_rgba(26,182,240,.7)]"></div>
      </div>
      <div className="absolute left-[14%] top-[64%] w-1 h-1 rounded-full bg-ice-200 pulse-soft" style={{ animationDelay: '1s' }}></div>
      <div className="absolute right-[24%] top-[78%] w-1 h-1 rounded-full bg-white/50 pulse-soft" style={{ animationDelay: '1.6s' }}></div>
    </div>);

}

// ---------- Pricing rendering ----------
function PriceBlock({ pricing }) {
  if (pricing.kind === "quote") {
    return (
      <div className="flex flex-col gap-0.5">
        <span className="text-xl font-display font-semibold cy-text leading-none whitespace-nowrap">Valor Sob Consulta</span>
        {pricing.label &&
          <span className="text-[11px] text-ice-300 font-mono">{pricing.label}</span>
        }
      </div>);

  }
  if (pricing.kind === "fixed") {
    return (
      <div>
        <div className="text-2xl font-display font-bold text-white tracking-tight whitespace-nowrap">{pricing.value}</div>
        <div className="text-[11px] uppercase tracking-[.18em] text-slate-400 font-mono mt-0.5">{pricing.caption}</div>
      </div>);

  }
  // tiered
  return (
    <div className="space-y-1 w-full">
      {pricing.heading &&
        <div className="text-[10px] uppercase tracking-[.12em] text-cy-300/90 font-mono mb-1.5 leading-snug">{pricing.heading}</div>
      }
      {pricing.tiers.map((t, i) =>
      <div key={i} className="flex items-baseline justify-between gap-3">
          <span className="text-[10.5px] uppercase tracking-[.14em] text-slate-400 font-mono">{t.label}</span>
          <span className={`font-display font-semibold whitespace-nowrap ${i === 0 ? "text-lg text-white" : "text-sm text-slate-200"}`}>{t.value}</span>
        </div>
      )}
      {pricing.note &&
        <div className="flex items-start gap-1.5 mt-2 pt-2 border-t border-white/10 text-[10.5px] text-ice-300/85 leading-snug">
          <span className="font-mono">{pricing.note}</span>
        </div>
      }
    </div>);

}

// ---------- Glossary term tooltip ----------
// Tooltip renders into a portal at document.body so it escapes any
// `overflow: hidden` / `transform` / stacking-context clipping from ancestors.
function Term({ term, display }) {
  const def = (window.GLOSSARY || {})[term];
  const [open, setOpen] = useState(false);
  const [pos, setPos] = useState({ x: 0, y: 0, flipDown: false });
  const triggerRef = useRef(null);

  const computePosition = React.useCallback(() => {
    if (!triggerRef.current) return;
    const r = triggerRef.current.getBoundingClientRect();
    const flipDown = r.top < 160;
    const x = r.left + r.width / 2;
    const y = flipDown ? r.bottom + 8 : r.top - 8;
    setPos({ x, y, flipDown });
  }, []);

  // While open: track scroll/resize/wheel so the tooltip follows the trigger.
  useEffect(() => {
    if (!open) return;
    computePosition();
    const onScroll = () => computePosition();
    window.addEventListener('scroll', onScroll, true);
    window.addEventListener('resize', onScroll);
    return () => {
      window.removeEventListener('scroll', onScroll, true);
      window.removeEventListener('resize', onScroll);
    };
  }, [open, computePosition]);

  // Close on outside click and ESC
  useEffect(() => {
    if (!open) return;
    const onDoc = (e) => {
      if (triggerRef.current && !triggerRef.current.contains(e.target)) setOpen(false);
    };
    const onKey = (e) => {if (e.key === "Escape") setOpen(false);};
    document.addEventListener('mousedown', onDoc);
    document.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('mousedown', onDoc);
      document.removeEventListener('keydown', onKey);
    };
  }, [open]);

  if (!def) {
    return <span>{display || term}</span>;
  }

  const tooltip = open && ReactDOM.createPortal(
    <div
      role="tooltip"
      className={`term-tip-portal ${pos.flipDown ? 'term-tip-down' : 'term-tip'}`}
      style={{
        position: 'fixed',
        left: pos.x,
        top: pos.y,
        transform: pos.flipDown ? 'translate(-50%, 0)' : 'translate(-50%, -100%)',
        zIndex: 9999,
        pointerEvents: 'none',
        width: 'min(280px, calc(100vw - 32px))'
      }}>
      
      <div className="rounded-lg border px-3.5 py-3 shadow-[0_16px_44px_rgba(0,0,0,.7)]"
      style={{ background: '#0C111B', borderColor: 'rgba(63,196,250,.45)' }}>
        <div className="font-display text-[12.5px] font-semibold text-cy-200 mb-1" style={{ letterSpacing: '0', textTransform: 'none' }}>{term}</div>
        <div
          className="text-[12.5px] leading-relaxed text-ice-100"
          style={{ fontFamily: 'Inter, system-ui, sans-serif', letterSpacing: '0', textTransform: 'none', fontWeight: 400 }}>
          {def}</div>
      </div>
    </div>,
    document.body
  );

  return (
    <span
      ref={triggerRef}
      className="relative inline"
      onMouseEnter={() => setOpen(true)}
      onMouseLeave={() => setOpen(false)}>
      
      <span
        role="button"
        tabIndex={0}
        onClick={(e) => {e.stopPropagation();setOpen((o) => !o);}}
        onKeyDown={(e) => {if (e.key === 'Enter' || e.key === ' ') {e.preventDefault();setOpen((o) => !o);}}}
        className="cursor-help inline-flex items-baseline gap-[3px] border-b border-dotted border-cy-400/55 hover:border-cy-300 transition-colors">
        
        <span>{display || term}</span>
        <span
          aria-hidden="true"
          className="inline-flex items-center justify-center w-[12px] h-[12px] rounded-full border border-cy-400/45 text-[8.5px] leading-none font-mono text-cy-200/90 translate-y-[-1px] select-none"
          style={{ fontFamily: 'JetBrains Mono, ui-monospace, monospace' }}>
          ?</span>
      </span>
      {tooltip}
    </span>);

}

// Walk a string and wrap every glossary term in a <Term> element.
// Returns either the original string (no matches) or an array of strings+elements.
function renderWithTerms(text) {
  if (typeof text !== 'string' || !window.GLOSSARY) return text;
  const keys = Object.keys(window.GLOSSARY).sort((a, b) => b.length - a.length);
  if (keys.length === 0) return text;
  const escaped = keys.map((k) => k.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
  const re = new RegExp('(' + escaped.join('|') + ')', 'gi');
  const wordChar = /[\w\u00C0-\u017F]/;
  const parts = [];
  let last = 0;
  let m;
  while ((m = re.exec(text)) !== null) {
    const before = text[m.index - 1];
    const after = text[m.index + m[0].length];
    // Skip if embedded inside a longer word (e.g. 'API' inside 'APIzer')
    if (before && wordChar.test(before) || after && wordChar.test(after)) continue;
    if (m.index > last) parts.push(text.slice(last, m.index));
    const canonical = keys.find((k) => k.toLowerCase() === m[0].toLowerCase()) || m[0];
    parts.push(<Term key={parts.length + ':' + m.index} term={canonical} display={m[0]} />);
    last = m.index + m[0].length;
  }
  if (parts.length === 0) return text;
  if (last < text.length) parts.push(text.slice(last));
  return parts;
}

// ---------- Service card ----------
function ServiceCard({ svc, onQuote, variant = "default" }) {
  const accent = {
    software: { ring: "rgba(26,182,240,.40)", chip: "bg-cy-400/10 text-cy-200 border-cy-400/30", dot: "#1AB6F0", icon: "Code2" },
    redes: { ring: "rgba(26,182,240,.35)", chip: "bg-cy-400/10 text-cy-100 border-cy-400/25", dot: "#3FC4FA", icon: "Network" },
    telecom: { ring: "rgba(124,218,254,.45)", chip: "bg-cy-200/10 text-cy-100 border-cy-200/25", dot: "#7CDAFE", icon: "RadioTower" },
    smart: { ring: "rgba(217,225,236,.30)", chip: "bg-white/5 text-ice-200 border-white/15", dot: "#D9E1EC", icon: "Home" },
    suporte: { ring: "rgba(217,225,236,.22)", chip: "bg-white/5 text-ice-200 border-white/10", dot: "#AEB9C8", icon: "Wrench" }
  }[svc.category];

  return (
    <article
      className="card-hover relative overflow-hidden rounded-2xl border border-white/10 bg-gradient-to-b from-ink-700/60 to-ink-800/80 backdrop-blur-sm fade-up"
      style={{ boxShadow: `inset 0 1px 0 rgba(255,255,255,.05)` }}>
      
      {/* corner accent line */}
      <div className="absolute top-0 left-0 h-px w-24" style={{ background: `linear-gradient(90deg, ${accent.dot}, transparent)` }} />
      <div className="absolute top-0 left-0 w-px h-24" style={{ background: `linear-gradient(180deg, ${accent.dot}, transparent)` }} />

      <div className="p-6 flex flex-col gap-5 h-full">
        {/* header row */}
        <div className="flex items-start justify-between gap-3">
          <div className="flex items-center gap-3">
            <div
              className="w-10 h-10 rounded-lg flex items-center justify-center border"
              style={{ borderColor: accent.ring, background: 'rgba(255,255,255,.02)' }}>
              
              <Icon name={accent.icon} size={18} />
            </div>
            <div>
              <div className="text-[10px] uppercase tracking-[.22em] text-slate-400 font-mono">{svc.code}</div>
              <div className="text-[11px] text-slate-300">{svc.badge}</div>
            </div>
          </div>
          {svc.sla &&
            <span className={`text-[10px] uppercase tracking-[.18em] font-mono px-2 py-1 rounded-full border ${accent.chip}`}>
              {svc.sla}
            </span>
          }
        </div>

        {/* title + description */}
        <div className="space-y-2">
          <h3 className="font-display font-semibold text-[19px] leading-snug text-white text-balance">{svc.title}</h3>
          <p className="text-[13.5px] leading-relaxed text-slate-300/90 text-pretty">{renderWithTerms(svc.short)}</p>
        </div>

        {/* deliverables */}
        <ul className="space-y-1.5">
          {svc.deliverables.map((d, i) =>
          <li key={i} className="flex items-start gap-2 text-[12.5px] text-slate-300/85">
              <span className="mt-1.5 w-1 h-1 rounded-full flex-shrink-0" style={{ background: accent.dot }} />
              <span>{renderWithTerms(d)}</span>
            </li>
          )}
        </ul>

        {/* tags */}
        <div className="flex flex-wrap gap-1.5">
          {svc.tags.map((t, i) =>
          <span key={i} className="text-[10.5px] font-mono uppercase tracking-wider px-2 py-1 rounded border border-white/10 text-slate-300 bg-white/[.02]">
              {renderWithTerms(t)}
            </span>
          )}
        </div>

        {/* footer: price stacked above full-width CTA */}
        <div className="mt-auto pt-5 border-t border-white/10 flex flex-col gap-4">
          <PriceBlock pricing={svc.pricing} />
          <button
            onClick={() => onQuote(svc)}
            className="group inline-flex items-center justify-center gap-2 w-full px-4 py-2.5 rounded-lg bg-cy-400 text-ink-950 hover:bg-cy-300 transition font-medium text-[13px] whitespace-nowrap">
            Solicitar Serviço
            
            <Icon name="ArrowUpRight" size={14} />
          </button>
        </div>
      </div>
    </article>);

}

// ---------- Quote modal ----------
function QuoteModal({ service, onClose }) {
  const [form, setForm] = useState({ nome: "", empresa: "", whatsapp: "", demanda: "" });
  const [state, setState] = useState("idle"); // idle | sending | success | error
  const firstRef = useRef(null);

  useEffect(() => {
    if (service) setTimeout(() => firstRef.current?.focus(), 80);
    const onKey = (e) => {if (e.key === "Escape") onClose();};
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [service, onClose]);

  if (!service) return null;

  const onSubmit = (e) => {
    e.preventDefault();
    if (!form.nome || !form.whatsapp) return;
    setState("sending");
    // Build a structured WhatsApp message and open it in a new tab.
    const lines = [
    `Olá, equipe SUN TECH! Vim pelo site solicitar orçamento:`,
    ``,
    `Serviço: ${service.code} — ${service.title}`,
    `Nome: ${form.nome}`];

    if (form.empresa) lines.push(`Empresa: ${form.empresa}`);
    lines.push(`WhatsApp: ${form.whatsapp}`);
    if (form.demanda) {
      lines.push(``, `Detalhes:`, form.demanda);
    }
    const phone = typeof window !== 'undefined' && window.WHATSAPP_PHONE || "5534999999999";
    const url = `https://wa.me/${phone}?text=${encodeURIComponent(lines.join("\n"))}`;
    window.open(url, "_blank", "noopener,noreferrer");
    setState("success");
  };

  return (
    <div className="fixed inset-0 z-50 flex items-end sm:items-center justify-center p-0 sm:p-6">
      {/* overlay */}
      <div className="absolute inset-0 bg-ink-950/92 backdrop-blur-sm" onClick={onClose} />
      <div className="relative w-full max-w-xl rounded-t-3xl sm:rounded-3xl border border-white/10 bg-ink-900 overflow-hidden noise">
        {/* top accent */}
        <div className="absolute top-0 left-0 right-0 h-px bg-gradient-to-r from-cy-400/70 via-cy-200/50 to-transparent" />
        <div className="absolute -top-24 -right-24 w-64 h-64 rounded-full"
        style={{ background: 'radial-gradient(circle, rgba(26,182,240,.28), rgba(26,182,240,0) 70%)' }} />

        <div className="relative p-6 sm:p-8">
          <div className="flex items-start justify-between gap-4 mb-5">
            <div>
              <div className="text-[10px] uppercase tracking-[.22em] text-slate-400 font-mono">{service.code} · Solicitação de orçamento</div>
              <h3 className="font-display font-semibold text-2xl text-white mt-1 leading-tight">{service.title}</h3>
            </div>
            <button onClick={onClose} className="w-9 h-9 rounded-lg border border-white/10 hover:bg-white/5 flex items-center justify-center text-slate-300">
              <Icon name="X" size={16} />
            </button>
          </div>

          {state !== "success" ?
          <form onSubmit={onSubmit} className="space-y-4">
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <Field label="Nome completo *">
                  <input ref={firstRef} required value={form.nome} onChange={(e) => setForm({ ...form, nome: e.target.value })}
                className="modal-input" placeholder="João Silva" />
                </Field>
                <Field label="Empresa">
                  <input value={form.empresa} onChange={(e) => setForm({ ...form, empresa: e.target.value })}
                className="modal-input" placeholder="ACME Ltda." />
                </Field>
              </div>
              <Field label="WhatsApp *">
                <input required value={form.whatsapp} onChange={(e) => setForm({ ...form, whatsapp: e.target.value })}
              className="modal-input" placeholder="(34) 9 0000-0000" />
              </Field>
              <Field label="Descreva sua demanda">
                <textarea value={form.demanda} onChange={(e) => setForm({ ...form, demanda: e.target.value })}
              rows={4} className="modal-input resize-none" placeholder="Conte brevemente o cenário, o número de estações ou o problema que precisa resolver." />
              </Field>

              <div className="flex items-center gap-3 pt-2">
                <button type="submit" disabled={state === "sending"}
              className="flex-1 inline-flex items-center justify-center gap-2 py-3 px-5 rounded-xl font-medium text-ink-950 transition disabled:opacity-60 hover:brightness-110"
              style={{ background: 'linear-gradient(95deg,#7CDAFE,#1AB6F0 60%,#0E97CC)' }}>
                  {state === "sending" ?
                <><Icon name="Loader2" size={16} className="animate-spin" /> Abrindo WhatsApp…</> :
                <><Icon name="MessageCircle" size={16} /> Enviar pelo WhatsApp</>}
                </button>
                <span className="text-[11px] text-slate-400 font-mono leading-snug max-w-[44%]">
                  Sua mensagem abre direto no WhatsApp da equipe.
                </span>
              </div>
            </form> :

          <div className="py-4 fade-up">
              <div className="w-14 h-14 mx-auto rounded-full flex items-center justify-center border border-cy-400/40"
            style={{ background: 'radial-gradient(circle, rgba(26,182,240,.28), transparent 70%)' }}>
                <Icon name="Check" size={26} />
              </div>
              <div className="text-center mt-5 space-y-2">
                <h4 className="font-display text-xl text-white">WhatsApp aberto em nova aba</h4>
                <p className="text-sm text-ice-200/85 leading-relaxed">
                  Sua mensagem foi pré-preenchida. Basta apertar enviar.<br />
                  Caso o WhatsApp não tenha aberto, verifique se há bloqueio de pop-ups.
                </p>
                <button onClick={onClose} className="mt-4 inline-flex items-center gap-2 px-5 py-2.5 rounded-lg border border-white/10 hover:bg-white/5 text-ice-100 text-sm">
                  Fechar
                </button>
              </div>
            </div>
          }
        </div>
      </div>
      <style>{`
        .modal-input {
          width: 100%;
          background: rgba(255,255,255,.03);
          border: 1px solid rgba(255,255,255,.08);
          border-radius: 10px;
          padding: 12px 14px;
          font-size: 14px;
          color: #E6EAF2;
          outline: none;
          transition: border-color .15s, background .15s;
        }
        .modal-input::placeholder { color: rgba(180,190,210,.4); }
        .modal-input:focus {
          border-color: rgba(26,182,240,.55);
          background: rgba(26,182,240,.06);
        }
      `}</style>
    </div>);

}
function Field({ label, children }) {
  return (
    <label className="block">
      <span className="block text-[11px] uppercase tracking-[.18em] text-slate-400 font-mono mb-1.5">{label}</span>
      {children}
    </label>);

}

// ---------- Legal modal: Terms of Service + Privacy Policy ----------
function LegalModal({ doc, onClose, onSwitch }) {
  const scrollRef = useRef(null);

  useEffect(() => {
    if (!doc) return;
    // Reset scroll on doc change
    if (scrollRef.current) scrollRef.current.scrollTop = 0;
    // Lock body scroll
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    const onKey = (e) => {if (e.key === "Escape") onClose();};
    document.addEventListener("keydown", onKey);
    return () => {
      document.body.style.overflow = prev;
      document.removeEventListener("keydown", onKey);
    };
  }, [doc, onClose]);

  if (!doc) return null;

  const content = doc === "terms" ? window.LEGAL_TERMS : window.LEGAL_PRIVACY;
  const otherDoc = doc === "terms" ? "privacy" : "terms";
  const otherLabel = doc === "terms" ? "Ver Política de Privacidade" : "Ver Termos de Serviço";

  return (
    <div className="fixed inset-0 z-50 flex items-stretch sm:items-center justify-center p-0 sm:p-6">
      <div className="absolute inset-0 bg-ink-950/85 backdrop-blur-md" onClick={onClose} />

      <div className="relative w-full sm:max-w-3xl sm:max-h-[88vh] flex flex-col rounded-none sm:rounded-3xl border border-white/10 bg-gradient-to-b from-ink-800/95 to-ink-900/98 overflow-hidden">
        {/* top accent */}
        <div className="absolute top-0 left-0 right-0 h-px bg-gradient-to-r from-cy-400/70 via-cy-200/40 to-transparent z-10" />

        {/* header */}
        <div className="relative shrink-0 px-6 sm:px-10 pt-8 pb-6 border-b border-white/10">
          <div className="flex items-start justify-between gap-4">
            <div className="flex-1 min-w-0">
              <div className="text-[10px] uppercase tracking-[.22em] text-cy-300 font-mono">
                /// SUN TECH &amp; GEEK LTDA · documento legal
              </div>
              <h2 className="font-display font-semibold text-[26px] sm:text-3xl text-white mt-2 leading-tight tracking-tight">
                {content.title}
              </h2>
              <p className="text-[13px] text-ice-200/80 mt-2 leading-relaxed max-w-xl">{content.subtitle}</p>
              <div className="text-[10px] uppercase tracking-[.18em] text-ice-400 font-mono mt-3">{content.updated}</div>
            </div>
            <button onClick={onClose} className="w-9 h-9 rounded-lg border border-white/10 hover:bg-white/5 flex items-center justify-center text-ice-200 shrink-0">
              <Icon name="X" size={16} />
            </button>
          </div>
        </div>

        {/* scrollable body */}
        <div ref={scrollRef} className="flex-1 min-h-0 overflow-y-auto px-6 sm:px-10 py-6">
          <div className="space-y-6 max-w-2xl">
            {content.sections.map((s, i) =>
            <section key={i} className="space-y-2">
                <h3 className="font-display font-semibold text-[15px] text-white tracking-tight">{s.title}</h3>
                <div className="space-y-2 text-[13px] text-ice-200/85 leading-relaxed">
                  {s.body.map((p, j) =>
                <p key={j} className="text-pretty">{p}</p>
                )}
                </div>
              </section>
            )}
          </div>
          <div className="h-6" />
        </div>

        {/* footer actions */}
        <div className="relative shrink-0 px-6 sm:px-10 py-4 border-t border-white/10 bg-ink-900/60 flex items-center justify-between gap-3">
          <button onClick={() => onSwitch(otherDoc)} className="inline-flex items-center gap-2 text-[12px] text-ice-200 hover:text-white transition font-mono">
            <Icon name="ArrowLeftRight" size={13} />
            {otherLabel}
          </button>
          <div className="flex items-center gap-2">
            <a href="mailto:contato@suntech-br.com" className="hidden sm:inline-flex items-center gap-2 px-3.5 py-2 rounded-lg border border-white/10 hover:bg-white/5 text-ice-100 text-[12.5px]">
              <Icon name="Mail" size={13} />
              Tirar dúvida
            </a>
            <button onClick={onClose} className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-cy-400 text-ink-950 hover:bg-cy-300 font-medium text-[12.5px] transition">
              Entendi
              <Icon name="Check" size={13} />
            </button>
          </div>
        </div>
      </div>
    </div>);

}

Object.assign(window, { Icon, LogoMark, OrbitalBackdrop, ServiceCard, QuoteModal, LegalModal, Field, PriceBlock, Term, renderWithTerms });