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

// ---------- Logo ----------
function DMLogo() {
  return (
    <div className="dm-logo">
      <span className="dm-logo-mark"></span>
      <span>DictaMedic<span style={{ color: "var(--accent-ink)" }}>.ai</span></span>
    </div>
  );
}

// ---------- Lang toggle ----------
function LangToggle({ lang, setLang }) {
  return (
    <div className="dm-lang" role="group" aria-label="Language">
      <button className={lang === "es" ? "active" : ""} onClick={() => setLang("es")}>ES</button>
      <button className={lang === "en" ? "active" : ""} onClick={() => setLang("en")}>EN</button>
    </div>
  );
}

// ---------- Nav ----------
function Nav({ t, lang, setLang }) {
  return (
    <nav className="dm-nav">
      <div className="dm-container dm-nav-inner">
        <DMLogo />
        <div className="dm-nav-links">
          <a href="#how">{t.nav.howItWorks}</a>
          <a href="#product">{t.nav.product}</a>
          <a href="#privacy">{t.nav.privacy}</a>
          <a href="#faq">{t.nav.faq}</a>
        </div>
        <div className="dm-nav-right">
          <LangToggle lang={lang} setLang={setLang} />
          <a href="#cta" className="dm-btn dm-btn-primary" style={{ padding: "10px 18px", fontSize: 14 }}>
            {t.nav.demo}
            <span className="dm-btn-arrow"></span>
          </a>
        </div>
      </div>
    </nav>
  );
}

// ---------- Phone mockup with report ----------
function PhoneReport({ t, recording = false }) {
  const r = t.product.report;
  return (
    <div className="dm-phone-shell" style={{ width: 320, margin: "0 auto" }}>
      <div className="dm-phone-screen" style={{ height: 660, position: "relative", display: "flex", flexDirection: "column" }}>
        {/* Status bar */}
        <div style={{ display: "flex", justifyContent: "space-between", padding: "14px 26px 10px", fontSize: 12, fontWeight: 600, color: "#0b1220", flexShrink: 0 }}>
          <span>11:24</span>
          <span style={{ display: "flex", gap: 4, alignItems: "center" }}>
            <span style={{ display: "inline-block", width: 14, height: 8, border: "1px solid #0b1220", borderRadius: 2, position: "relative" }}>
              <span style={{ position: "absolute", inset: 1, background: "#0b1220", borderRadius: 1, width: "70%" }}></span>
            </span>
          </span>
        </div>
        {/* App header */}
        <div style={{ padding: "14px 22px 16px", borderBottom: "1px solid #e2e8f3", display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 10, flexShrink: 0 }}>
          <div style={{ minWidth: 0, flex: 1 }}>
            <div style={{ fontFamily: "var(--mono)", fontSize: 9, letterSpacing: "0.10em", textTransform: "uppercase", color: "#6b7280", whiteSpace: "nowrap" }}>
              {r.date}
            </div>
            <div style={{ fontFamily: "var(--serif)", fontSize: 17, fontWeight: 500, color: "#0b1220", marginTop: 4, letterSpacing: "-0.01em" }}>
              {r.patient}
            </div>
          </div>
          <div style={{ fontFamily: "var(--mono)", fontSize: 10, color: "#6b7280", whiteSpace: "nowrap", paddingTop: 2 }}>{r.duration}</div>
        </div>
        {/* Sections */}
        <div style={{ padding: "6px 22px 90px", overflow: "hidden", flex: 1 }}>
          {r.sections.map((s, i) => (
            <div key={i} style={{ paddingTop: 12, paddingBottom: 12, borderBottom: i < r.sections.length - 1 ? "1px dashed #e2e8f3" : "none" }}>
              <div style={{ fontFamily: "var(--mono)", fontSize: 9, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--accent-ink)", marginBottom: 6 }}>
                {s.label}
              </div>
              <div style={{ fontSize: 12, lineHeight: 1.5, color: "#1f2937", fontFamily: "var(--serif)" }}>
                {s.body}
              </div>
            </div>
          ))}
        </div>
        {/* Bottom action */}
        <div style={{ position: "absolute", bottom: 0, left: 0, right: 0, padding: "20px 22px 24px", background: "linear-gradient(180deg, transparent, #ffffff 30%)" }}>
          <div style={{ display: "flex", gap: 8 }}>
            <button style={{ flex: 1, background: "#0b1220", color: "#ffffff", border: 0, borderRadius: 999, padding: "10px 14px", fontSize: 12, fontWeight: 500 }}>
              {recording ? "■ Detener" : "Exportar"}
            </button>
            <button style={{ width: 38, height: 38, borderRadius: 999, border: "1px solid #e2e8f3", background: "transparent", padding: 0, display: "flex", alignItems: "center", justifyContent: "center" }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#0b1220" strokeWidth="1.6"><path d="M9 17h6M5 7h14M5 12h14M5 17h2"/></svg>
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

// ---------- Recording phone state (for hero/preview)  ----------
function PhoneRecording({ t }) {
  return (
    <div className="dm-phone-shell" style={{ width: 320, margin: "0 auto" }}>
      <div className="dm-phone-screen" style={{ height: 660, position: "relative", display: "flex", flexDirection: "column" }}>
        <div style={{ display: "flex", justifyContent: "space-between", padding: "14px 26px 10px", fontSize: 12, fontWeight: 600, color: "#0b1220", flexShrink: 0 }}>
          <span>11:24</span>
        </div>
        <div style={{ padding: "14px 22px 16px", borderBottom: "1px solid #e2e8f3", flexShrink: 0 }}>
          <div style={{ fontFamily: "var(--mono)", fontSize: 9, letterSpacing: "0.12em", textTransform: "uppercase", color: "#6b7280" }}>
            Consulta general
          </div>
          <div style={{ fontFamily: "var(--serif)", fontSize: 17, fontWeight: 500, color: "#0b1220", marginTop: 2 }}>
            Nueva grabación
          </div>
        </div>
        <div style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 32, padding: 24 }}>
          <div style={{ fontFamily: "var(--mono)", fontSize: 10, color: "#6b7280", letterSpacing: "0.12em" }}>GRABANDO</div>
          <div style={{ fontFamily: "var(--mono)", fontSize: 36, color: "#0b1220", fontWeight: 500, letterSpacing: "-0.02em" }}>
            04:38
          </div>
          <div className="dm-wave" style={{ height: 40, gap: 4 }}>
            {Array.from({ length: 18 }).map((_, i) => (
              <span key={i} style={{ width: 3, animationDelay: `${i * 0.05}s` }}></span>
            ))}
          </div>
          <div style={{ fontSize: 12, color: "#6b7280", textAlign: "center", maxWidth: 220, lineHeight: 1.5 }}>
            El audio se procesa en la UE y se elimina tras la transcripción.
          </div>
        </div>
        <div style={{ padding: "16px 22px 28px", display: "flex", justifyContent: "center", gap: 10 }}>
          <button style={{ width: 64, height: 64, borderRadius: "50%", background: "#2e5bff", border: "4px solid #ffffff", boxShadow: "0 0 0 1px #2e5bff" }}>
            <span style={{ display: "block", width: 18, height: 18, background: "#ffffff", margin: "auto", borderRadius: 2 }}></span>
          </button>
        </div>
      </div>
    </div>
  );
}

// ---------- Onboarding carousel (slidable iOS frame) ----------
function OnboardingCarousel({ width = 320 }) {
  const slides = [
    "onboarding-screenshoot-image/Onboarding_1_Dictation_v2.png",
    "onboarding-screenshoot-image/Onboarding_2_Records_v2.png",
    "onboarding-screenshoot-image/Onboarding_3_Anywhere_v2.png"
  ];
  const labels = ["Dictation", "Records", "Anywhere"];
  const [idx, setIdx] = useState(0);
  const [drag, setDrag] = useState(0);
  const [dragging, setDragging] = useState(false);
  const startX = useRef(null);
  const height = Math.round(width * (874 / 402));

  useEffect(() => {
    if (dragging) return;
    const id = setTimeout(() => setIdx((i) => (i + 1) % slides.length), 5200);
    return () => clearTimeout(id);
  }, [idx, dragging]);

  const begin = (x) => { startX.current = x; setDrag(0); setDragging(true); };
  const move = (x) => { if (startX.current != null) setDrag(x - startX.current); };
  const end = () => {
    if (startX.current == null) return;
    const threshold = width * 0.18;
    if (drag < -threshold) setIdx((i) => Math.min(slides.length - 1, i + 1));
    else if (drag > threshold) setIdx((i) => Math.max(0, i - 1));
    startX.current = null;
    setDrag(0);
    setDragging(false);
  };

  const offset = -idx * 100 + (drag / width) * 100;

  const surface = (
    <div
      onMouseDown={(e) => begin(e.clientX)}
      onMouseMove={(e) => startX.current != null && move(e.clientX)}
      onMouseUp={end}
      onMouseLeave={end}
      onTouchStart={(e) => begin(e.touches[0].clientX)}
      onTouchMove={(e) => move(e.touches[0].clientX)}
      onTouchEnd={end}
      style={{ width: "100%", height: "100%", position: "relative", overflow: "hidden", userSelect: "none", cursor: dragging ? "grabbing" : "grab", touchAction: "pan-y" }}
    >
      <div style={{
        display: "flex", width: `${slides.length * 100}%`, height: "100%",
        transform: `translateX(${offset / slides.length}%)`,
        transition: dragging ? "none" : "transform 0.55s cubic-bezier(0.32, 0.72, 0, 1)"
      }}>
        {slides.map((src, i) => (
          <div key={i} style={{ width: `${100 / slides.length}%`, height: "100%", flexShrink: 0 }}>
            <img src={src} alt={labels[i]} draggable={false}
              style={{ width: "100%", height: "100%", objectFit: "cover", objectPosition: "top center", display: "block", pointerEvents: "none" }} />
          </div>
        ))}
      </div>
    </div>
  );

  return (
    <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 18 }}>
      <div style={{ width, height, borderRadius: 44, overflow: "hidden", boxShadow: "0 40px 80px rgba(0,0,0,0.18), 0 0 0 1px rgba(0,0,0,0.12)" }}>{surface}</div>
      <div style={{ display: "flex", gap: 8, alignItems: "center" }} role="tablist" aria-label="Onboarding slides">
        {slides.map((_, i) => (
          <button key={i} role="tab" aria-selected={i === idx} aria-label={labels[i]}
            onClick={() => { startX.current = null; setDragging(false); setIdx(i); }}
            style={{
              width: i === idx ? 22 : 8, height: 8, borderRadius: 999,
              border: 0, padding: 0,
              background: i === idx ? "var(--accent)" : "var(--line)",
              transition: "width 0.25s, background 0.25s"
            }} />
        ))}
      </div>
    </div>
  );
}

// ---------- Footer ----------
function Footer({ t }) {
  return (
    <footer className="dm-footer">
      <div className="dm-container">
        <div className="dm-footer-grid">
          <div>
            <DMLogo />
            <p style={{ marginTop: 16, color: "var(--muted)", fontSize: 14, maxWidth: 320, lineHeight: 1.6 }}>
              {t.footer.tagline}
            </p>
          </div>
          {t.footer.cols.map((col, i) => (
            <div key={i}>
              <h4>{col.h}</h4>
              <ul>
                {col.links.map((l, j) => <li key={j}><a href={l.href}>{l.label}</a></li>)}
              </ul>
            </div>
          ))}
        </div>
        <div className="dm-footer-bottom">
          <span>{t.footer.copyright}</span>
          <span className="dm-mono">v0.4 · Beta · ES</span>
        </div>
      </div>
    </footer>
  );
}

// ---------- FAQ ----------
function FAQSection({ t }) {
  return (
    <section id="faq" className="dm-section" style={{ padding: "var(--section-pad, 96px) 0", background: "var(--bg)" }}>
      <div className="dm-container">
        <div className="dm-section-head">
          <div className="label dm-eyebrow">{t.sectionLabels.faq}</div>
          <h2 className="title">{t.faq.title}</h2>
        </div>
        <div style={{ maxWidth: 880, marginLeft: "auto" }}>
          {t.faq.items.map((item, i) => (
            <details key={i} className="dm-faq-item" open={i === 0}>
              <summary>
                <div style={{ display: "flex", gap: 24, alignItems: "flex-start", flex: 1 }}>
                  <span className="dm-mono" style={{ minWidth: 32 }}>{String(i + 1).padStart(2, "0")}</span>
                  <span className="dm-faq-q">{item.q}</span>
                </div>
                <span className="dm-faq-plus">+</span>
              </summary>
              <div className="dm-faq-a">{item.a}</div>
            </details>
          ))}
        </div>
      </div>
    </section>
  );
}

// ---------- CTA ----------
function CTASection({ t }) {
  const [email, setEmail] = useState("");
  const [status, setStatus] = useState("idle"); // idle | sending | sent | error
  const [errorMsg, setErrorMsg] = useState("");

  async function handleSubmit(e) {
    e.preventDefault();
    if (!email || status === "sending") return;
    setStatus("sending");
    setErrorMsg("");
    try {
      const res = await fetch("/api/subscribe", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email }),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error(data.error || "Send failed");
      }
      setStatus("sent");
    } catch (err) {
      setStatus("error");
      setErrorMsg(err.message || "Send failed");
    }
  }

  return (
    <section id="cta" className="dm-section" style={{ padding: "120px 0", background: "var(--bg-elev)" }}>
      <div className="dm-container-narrow" style={{ textAlign: "center" }}>
        <div className="dm-eyebrow" style={{ marginBottom: 20 }}>{t.cta.eyebrow}</div>
        <h2 className="dm-serif" style={{ fontSize: "clamp(36px, 5vw, 60px)", lineHeight: 1.05, margin: "0 0 20px", letterSpacing: "-0.025em" }}>
          {t.cta.title}
        </h2>
        <p style={{ fontSize: 18, color: "var(--muted)", maxWidth: 580, margin: "0 auto 36px", lineHeight: 1.55 }}>
          {t.cta.sub}
        </p>
        {status === "sent" ? (
          <div style={{ padding: 24, border: "1px solid var(--line)", borderRadius: 16, maxWidth: 460, margin: "0 auto", background: "var(--bg)" }}>
            <div className="dm-eyebrow" style={{ marginBottom: 6 }}>{t.cta.successEyebrow}</div>
            <div style={{ fontFamily: "var(--serif)", fontSize: 20 }}>{t.cta.successMessage}</div>
          </div>
        ) : (
          <form
            onSubmit={handleSubmit}
            style={{ display: "flex", gap: 8, maxWidth: 460, margin: "0 auto", padding: 6, border: "1px solid var(--line)", borderRadius: 999, background: "var(--bg)" }}
          >
            <input
              type="email"
              required
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder={t.cta.emailPlaceholder}
              disabled={status === "sending"}
              style={{ flex: 1, border: 0, background: "transparent", padding: "10px 18px", fontSize: 15, outline: "none", color: "var(--ink)", fontFamily: "var(--sans)" }}
            />
            <button className="dm-btn dm-btn-primary" type="submit" disabled={status === "sending"}>
              {status === "sending" ? t.cta.sending : t.cta.button}
            </button>
          </form>
        )}
        {status === "error" && (
          <div style={{ marginTop: 14, fontSize: 13, color: "#c0392b", fontFamily: "var(--mono)" }}>
            {errorMsg || t.cta.errorFallback}
          </div>
        )}
        <div style={{ marginTop: 20, fontSize: 13, color: "var(--muted-2)", fontFamily: "var(--mono)", letterSpacing: "0.06em" }}>
          {t.cta.note}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { DMLogo, LangToggle, Nav, PhoneReport, PhoneRecording, OnboardingCarousel, Footer, FAQSection, CTASection });
