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

/* ============================================================
   Brand mark (DX) — re-drawn as SVG so it adapts to color
   ============================================================ */
const BrandMark = ({ color = "currentColor", size = 36 }) => (
  <svg width={size} height={size} viewBox="0 0 100 100" fill="none" aria-hidden="true">
    {/* D shape */}
    <path
      d="M22 14 L52 14 C70 14 80 26 80 46 C80 66 70 86 52 86 L22 86 Z M34 26 L34 74 L50 74 C60 74 67 64 67 50 C67 36 60 26 50 26 Z"
      fill={color}
    />
    {/* X stroke piercing right */}
    <path
      d="M62 14 L86 14 L72 50 L86 86 L62 86 L48 50 Z"
      fill={color}
    />
  </svg>
);

/* ============================================================
   Reveal-on-scroll wrapper
   ============================================================ */
const Reveal = ({ children, as: As = "div", className = "", delay = 0, ...rest }) => {
  const ref = useRef(null);
  const [seen, setSeen] = useState(false);
  useEffect(() => {
    const el = ref.current; if (!el) return;
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { setSeen(true); io.disconnect(); }
    }, { threshold: 0.15, rootMargin: "0px 0px -60px 0px" });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return (
    <As ref={ref} className={`reveal ${seen ? "in" : ""} ${className}`} style={{ transitionDelay: `${delay}ms` }} {...rest}>
      {children}
    </As>
  );
};

/* ============================================================
   Navigation
   ============================================================ */
const Nav = ({ t, lang, setLang, openModal }) => {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return (
    <nav className={`nav ${scrolled ? "scrolled" : ""}`}>
      <div className="wrap nav-inner">
        <a href="#top" className="brand" aria-label="Dowsnux">
          <img src="assets/logo-dx-color.png" alt="Dowsnux" className="brand-logo" />
          <span style={{
            fontFamily: "var(--f-display)",
            fontWeight: 600,
            letterSpacing: "0.04em",
            fontSize: 13,
          }}>DOWSNUX</span>
        </a>
        <ul className="nav-links">
          {t.nav.links.map(l => (
            <li key={l.id}><a href={`#${l.id}`}>{l.label}</a></li>
          ))}
        </ul>
        <div className="nav-actions">
          <div className="lang-toggle" role="group" aria-label="Language">
            <button className={lang === "pt" ? "active" : ""} onClick={() => setLang("pt")}>PT</button>
            <button className={lang === "en" ? "active" : ""} onClick={() => setLang("en")}>EN</button>
          </div>
          <button className="btn btn-primary btn-sm btn-arrow" onClick={openModal}>
            {t.nav.cta}
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 5l7 7-7 7"/></svg>
          </button>
        </div>
      </div>
    </nav>
  );
};

/* ============================================================
   Hero
   ============================================================ */
const HeroVisual = ({ v }) => (
  <div className="hero-visual">
    <div className="hero-chip chip-1">
      <span className="dot"></span>{v.chip1}
    </div>
    <div className="hero-chip chip-2">{v.chip2}</div>

    <div className="hero-stack">
      {/* Card 1 - code editor */}
      <div className="hero-card hc1">
        <div className="hc-head">
          <div className="hc-title">{v.codeTitle}</div>
          <div className="hc-dots"><span></span><span></span><span></span></div>
        </div>
        {v.codeLines.map((l, i) => (
          <div className="code-line" key={i}>
            <span className="tk-mut">{String(i+1).padStart(2,"0")} </span>
            {l.k && <span className="tk-key">{l.k}</span>}
            {l.v && <span>{l.v}</span>}
            {l.op && <span className="tk-mut">{l.op}</span>}
            {l.s && <span className="tk-str">{l.s}</span>}
            {i === v.codeLines.length - 1 && <span className="cursor"></span>}
          </div>
        ))}
      </div>

      {/* Card 2 - chat */}
      <div className="hero-card hc2">
        <div className="hc-head">
          <div className="hc-title">{v.chatTitle}</div>
          <span style={{ fontFamily:"var(--f-mono)", fontSize:10, color:"var(--ok)" }}>● live</span>
        </div>
        {v.chat.map((m, i) => (
          <div className={`chat-msg ${m.who}`} key={i}>
            <div className="chat-av">{m.av}</div>
            <div className="chat-bubble">{m.t}</div>
          </div>
        ))}
      </div>

      {/* Card 3 - metric */}
      <div className="hero-card hc3">
        <div className="hc-head">
          <div className="hc-title">{v.metricTitle}</div>
        </div>
        <div className="metric-row">
          <span className="m-val">{v.metric}</span>
          <span className="m-unit">{v.metricUnit}</span>
        </div>
        <div className="bar-row">
          {v.bars.map((b, i) => (
            <div key={i}>
              <div className="bar-label"><span>{b.label}</span><span>{b.val}%</span></div>
              <div className="bar"><i style={{ width: `${b.val}%` }}></i></div>
            </div>
          ))}
        </div>
      </div>
    </div>
  </div>
);

const Hero = ({ t, openModal }) => {
  const h = t.hero;
  return (
    <header className="hero" id="top">
      <div className="hero-bg"></div>
      <div className="hero-dots">
        <DottedSurface opacity={0.5} />
      </div>
      <div className="hero-grid-bg"></div>
      <div className="wrap hero-inner">
        <div>
          <span className="eyebrow">{h.eyebrow}</span>
          <h1>
            {h.h1Pre}{" "}
            <span className="accent">{h.h1Accent}</span>{" "}
            {h.h1Post}
          </h1>
          <p className="hero-sub">{h.sub}</p>
          <div className="hero-cta">
            <button className="btn btn-primary btn-arrow" onClick={openModal}>
              {h.cta}
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 5l7 7-7 7"/></svg>
            </button>
            <a href="#solucao" className="btn btn-ghost">{h.ctaSecondary}</a>
          </div>
          <div className="hero-cta-meta">
            {h.meta.map((m, i) => (
              <React.Fragment key={i}>
                {i > 0 && <span className="dot"></span>}
                <span>{m}</span>
              </React.Fragment>
            ))}
          </div>
        </div>
        <HeroVisual v={h.visual} />
      </div>
    </header>
  );
};

/* ============================================================
   Marquee (tech ticker)
   ============================================================ */
const Marquee = ({ items }) => {
  const list = [...items, ...items];
  return (
    <div className="marquee" aria-hidden="true">
      {[0,1].map(k => (
        <div className="marquee-track" key={k}>
          {list.map((it, i) => (
            <div className="marquee-item" key={`${k}-${i}`}>
              <span className="star">✦</span>{it}
            </div>
          ))}
        </div>
      ))}
    </div>
  );
};

/* ============================================================
   Value Proposition
   ============================================================ */
const ValueProp = ({ t }) => {
  const v = t.valueProp;
  return (
    <section className="section value-prop" id="solucao">
      <div className="wrap">
        <Reveal className="section-head">
          <span className="eyebrow">{v.eyebrow}</span>
          <h2>{v.h2}</h2>
        </Reveal>
        <Reveal delay={80}>
          <p>{v.p1}</p>
          <p>{v.p2}</p>
          <p>{v.p3}</p>
          <p>{v.p4Pre}<span className="highlight">{v.p4Highlight}</span></p>
        </Reveal>
      </div>
    </section>
  );
};

/* ============================================================
   Pain points - interactive checkable cards
   ============================================================ */
const Pain = ({ t, openModal }) => {
  const p = t.pain;
  const [checked, setChecked] = useState(new Set());
  const toggle = (i) => {
    const next = new Set(checked);
    next.has(i) ? next.delete(i) : next.add(i);
    setChecked(next);
  };
  const n = checked.size;
  let tally = p.tallyZero;
  if (n === 1) tally = p.tallyOne;
  else if (n >= p.items.length) tally = p.tallyAll;
  else if (n > 1) tally = p.tallyMany(n);

  return (
    <section className="section">
      <div className="wrap">
        <Reveal className="section-head">
          <span className="eyebrow">{p.eyebrow}</span>
          <h2>{p.h2}</h2>
          <p style={{ color: "var(--ink-muted)", fontSize: "var(--t-4)", maxWidth: 640 }}>{p.sub}</p>
        </Reveal>
        <div className="pain-grid">
          {p.items.map((it, i) => (
            <button
              key={i}
              type="button"
              className={`pain-card ${checked.has(i) ? "checked" : ""}`}
              onClick={() => toggle(i)}
              aria-pressed={checked.has(i)}
            >
              <span className="pain-check">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3">
                  <path d="M5 12l5 5L20 7"/>
                </svg>
              </span>
              <span>{it}</span>
            </button>
          ))}
        </div>
        <div className="pain-tally" role="status" aria-live="polite">
          <div className="pain-tally-text">{tally}</div>
          <button className="btn btn-primary btn-arrow" onClick={openModal}>
            {p.tallyCta}
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 5l7 7-7 7"/></svg>
          </button>
        </div>
      </div>
    </section>
  );
};

/* ============================================================
   Solution (Section 6)
   ============================================================ */
const Solution = ({ t }) => {
  const s = t.solution;
  return (
    <section className="section">
      <div className="wrap solution-layout">
        <Reveal className="section-head" style={{ marginBottom: 0 }}>
          <span className="eyebrow">{s.eyebrow}</span>
          <h2>{s.h2}</h2>
        </Reveal>
        <Reveal delay={80}>
          <div className="solution-body">
            {s.body.map((p, i) => <p key={i} dangerouslySetInnerHTML={{ __html: p.html }} />)}
          </div>
          <div className="solution-stats">
            {s.stats.map((st, i) => (
              <div className="stat" key={i}>
                <div className="stat-num">{st.num}</div>
                <div className="stat-label">{st.label}</div>
              </div>
            ))}
          </div>
        </Reveal>
      </div>
    </section>
  );
};

/* ============================================================
   Benefits (Section 7)
   ============================================================ */
const Benefits = ({ t }) => {
  const b = t.benefits;
  return (
    <section className="section" id="beneficios">
      <div className="wrap">
        <Reveal className="section-head">
          <span className="eyebrow">{b.eyebrow}</span>
          <h2>{b.h2}</h2>
        </Reveal>
        <div className="benefit-list">
          {b.items.map((it, i) => (
            <Reveal as="div" className="benefit-row" key={i} delay={i*40}>
              <div className="benefit-num">{String(i+1).padStart(2,"0")}</div>
              <div className="benefit-text">
                <h3>{it.t}</h3>
                <p>{it.d}</p>
              </div>
              <div className="benefit-icon">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                  <path d="M7 17L17 7M9 7h8v8"/>
                </svg>
              </div>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
};

Object.assign(window, {
  BrandMark, Reveal, Nav, Hero, Marquee, ValueProp, Pain, Solution, Benefits,
});
