/* ====================================================================
   Appril · Diagnóstico — app.jsx
   Landing + entrada al wizard + tweaks panel + tracking init
   ==================================================================== */

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "headlineVariant": "MAIN",
  "accent": "coral",
  "density": "comfortable",
  "showValidators": true,
  "estimatedTime": "2 min"
}/*EDITMODE-END*/;

const HEADLINE_VARIANTS = {
  MAIN: { h: AP.t("landing.hero.variants.MAIN.h"), tag: AP.t("landing.hero.variants.MAIN.tag") },
  A:    { h: AP.t("landing.hero.variants.A.h"),    tag: AP.t("landing.hero.variants.A.tag") },
  B:    { h: AP.t("landing.hero.variants.B.h"),    tag: AP.t("landing.hero.variants.B.tag") },
  C:    { h: AP.t("landing.hero.variants.C.h"),    tag: AP.t("landing.hero.variants.C.tag") }
};

const ACCENT_TOKENS = {
  coral: { c: "#FE345C", c700: "#DB1E44", c50: "#FFF0F3", c100: "#FFE1E8" },
  green: { c: "#0E8A5F", c700: "#066F4B", c50: "#E8F4EE", c100: "#D1EBDD" },
  blue:  { c: "#2A6FDB", c700: "#1F58B5", c50: "#EAF1FB", c100: "#D5E3F7" }
};

function applyAccent(accent) {
  const t = ACCENT_TOKENS[accent] || ACCENT_TOKENS.coral;
  const r = document.documentElement;
  r.style.setProperty("--coral",     t.c);
  r.style.setProperty("--coral-700", t.c700);
  r.style.setProperty("--coral-50",  t.c50);
  r.style.setProperty("--coral-100", t.c100);
}

function App() {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [screen, setScreen] = React.useState("landing");
  const [result, setResult] = React.useState(null);

  // Apply tweaks
  React.useEffect(() => { applyAccent(tweaks.accent); }, [tweaks.accent]);
  React.useEffect(() => { document.documentElement.dataset.density = tweaks.density; }, [tweaks.density]);

  // Tracking init: session id + page view (fire-and-forget)
  React.useEffect(() => {
    AP.getAnonymousSessionId();
    AP.captureUtm();
    AP.trackDiscoveryEvent({ event_name: "discovery_page_view" });
  }, []);

  const heroCopy = HEADLINE_VARIANTS[tweaks.headlineVariant] || HEADLINE_VARIANTS.MAIN;

  return (
    <React.Fragment>
      {screen === "landing" && (
        <Landing
          heroCopy={heroCopy}
          time={tweaks.estimatedTime}
          onStart={() => setScreen("wizard")}
        />
      )}

      <Wizard
        open={screen === "wizard"}
        onClose={() => setScreen("landing")}
        onFinish={(out) => { setResult(out); setScreen("result"); }}
        tweaks={tweaks}
      />

      {screen === "result" && result && (
        <ResultDashboard
          payload={result.payload}
          backend={result.backend}
          onClose={() => setScreen("landing")}
        />
      )}

      <TweaksPanel title="Tweaks">
        <TweakSection label="Hero">
          <TweakRadio
            label="Headline"
            value={tweaks.headlineVariant}
            onChange={(v) => setTweak("headlineVariant", v)}
            options={[
              { value: "MAIN", label: "Principal" },
              { value: "A",    label: "A" },
              { value: "B",    label: "B" },
              { value: "C",    label: "C" }
            ]}
          />
          <div style={{ fontSize: 12, color: "var(--muted)", padding: "4px 12px 8px", lineHeight: 1.4 }}>
            <strong style={{ color: "var(--ink)" }}>“{heroCopy.h}”</strong>
          </div>
          <TweakSelect
            label="Tiempo mostrado"
            value={tweaks.estimatedTime}
            onChange={(v) => setTweak("estimatedTime", v)}
            options={[
              { value: "2 min", label: "2 minutos" },
              { value: "3 min", label: "3 minutos" },
              { value: "",      label: "Sin tiempo" }
            ]}
          />
        </TweakSection>

        <TweakSection label="Estilo">
          <TweakRadio
            label="Acento"
            value={tweaks.accent}
            onChange={(v) => setTweak("accent", v)}
            options={[
              { value: "coral", label: "Coral" },
              { value: "green", label: "Verde" },
              { value: "blue",  label: "Azul" }
            ]}
          />
          <TweakRadio
            label="Densidad"
            value={tweaks.density}
            onChange={(v) => setTweak("density", v)}
            options={[
              { value: "comfortable", label: "Cómoda" },
              { value: "compact",     label: "Compacta" }
            ]}
          />
        </TweakSection>

        <TweakSection label="Contenido">
          <TweakToggle
            label="Validadores científicos"
            value={tweaks.showValidators}
            onChange={(v) => setTweak("showValidators", v)}
          />
        </TweakSection>

        <TweakSection label="Atajos">
          <TweakButton
            label="Reiniciar diagnóstico"
            onClick={() => {
              ["appril_disc_answers","appril_disc_contact","appril_disc_result"].forEach((k) => localStorage.removeItem(k));
              setResult(null);
              setScreen("landing");
            }}
          />
        </TweakSection>
      </TweaksPanel>
    </React.Fragment>
  );
}

/* ===================== Landing ===================== */
function Landing({ heroCopy, time, onStart }) {
  return (
    <React.Fragment>
      {/* Marca mínima en el top */}
      <header className="lp-mini">
        <div className="container lp-mini__inner">
          <div className="lp-mini__brand">
            <span className="lp-mini__title">{AP.t("landing.mini.title")}</span>
            <span className="lp-mini__by">{AP.t("landing.mini.by")} <a href="https://appril.co">Appril</a></span>
          </div>
          <a className="lp-mini__back" href="https://appril.co">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"><path d="M19 12H5M11 6l-6 6 6 6"/></svg>
            appril.co
          </a>
        </div>
      </header>

      {/* HERO */}
      <header className="lp-hero">
        <div className="container">
          <div className="lp-hero__inner">
            <div>
              <span className="lp-hero__pill">{heroCopy.tag} · {time || AP.t("landing.defaultTime")}</span>
              <h1>{heroCopy.h}</h1>
              <p className="lp-hero__sub">
                {AP.t("landing.hero.sub")}
              </p>
              <div className="lp-hero__cta">
                <button className="btn btn--primary btn--lg" onClick={onStart}>
                  {AP.t("common.calcCta")}
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
                </button>
              </div>
              <div className="lp-hero__meta">
                <span>{AP.t("landing.hero.metaNoReg")}</span>
                <span>·</span>
                <span>{AP.t("landing.hero.metaNoCard")}</span>
                <span>·</span>
                <span>{AP.t("landing.hero.metaInstant")}</span>
              </div>
            </div>

            <div className="lp-hero__visual" aria-hidden="true">
              <div className="lp-hero__shield">
                <span className="lp-hero__shieldLab">{AP.t("landing.hero.shieldLab")}</span>
                <span className="lp-hero__shieldVal">+USD 11.340</span>
                <span className="lp-hero__shieldNote">{AP.t("landing.hero.shieldNote")}</span>
              </div>

              <div className="lp-hero__cal">
                <div className="lp-hero__calHead">
                  <span>{AP.t("landing.hero.calWeek")}</span>
                  <span className="lp-hero__calOk">{AP.t("landing.hero.calConfirmed")}</span>
                </div>
                <div className="lp-hero__calGrid">
                  {["L","M","M","J","V","S","D"].map((d, i) => {
                    const states = ["ok","ok","risk","ok","ok","ok","empty"];
                    return (
                      <div key={i} className={"lp-hero__calCell s-" + states[i]}>
                        <span className="lp-hero__calDay">{d}</span>
                        <div className="lp-hero__calDots">
                          <span></span><span></span><span></span>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>

              <div className="lp-hero__chip lp-hero__chip--time">
                <span className="ico"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg></span>
                <div>
                  <div>{AP.t("landing.hero.chipTime")}</div>
                  <div className="muted">{AP.t("landing.hero.chipTimeSub")}</div>
                </div>
              </div>

              <div className="lp-hero__chip lp-hero__chip--peace">
                <span className="ico green">🧘</span>
                <div>
                  <div>{AP.t("landing.hero.chipPeace")}</div>
                  <div className="muted">{AP.t("landing.hero.chipPeaceSub")}</div>
                </div>
              </div>

              <div className="lp-hero__legend">{AP.t("landing.hero.legend")}</div>
            </div>
          </div>
        </div>
      </header>

      {/* PAIN */}
      <section className="lp-pain">
        <div className="container">
          <div className="lp-pain__head">
            <span className="eyebrow">{AP.t("landing.pain.eye")}</span>
            <h2>{AP.t("landing.pain.h")}</h2>
          </div>
          <div className="lp-pain__grid">
            {AP.t("landing.pain.items").map((t, i) => (
              <div key={i} className="lp-pain__card"><p>{t}</p></div>
            ))}
          </div>
          <div style={{ marginTop: 36, textAlign: "center" }}>
            <button className="btn btn--primary btn--lg" onClick={onStart}>{AP.t("common.calcCta")}</button>
          </div>
        </div>
      </section>

      {/* POSITIONING */}
      <section className="lp-pos">
        <div className="container">
          <div className="lp-pos__head">
            <span className="eyebrow green">{AP.t("landing.pos.eye")}</span>
            <h2>{AP.t("landing.pos.h")}</h2>
            <p style={{ marginTop: 18, color: "var(--ink-soft)", fontSize: 18, maxWidth: "60ch" }}>
              {AP.t("landing.pos.p")}
            </p>
          </div>
          <div className="lp-pos__cols">
            <div className="lp-pos__col">
              <div className="lp-pos__role">{AP.t("landing.pos.col1.role")}</div>
              <h3>{AP.t("landing.pos.col1.h")}</h3>
              <p>{AP.t("landing.pos.col1.p")}</p>
            </div>
            <div className="lp-pos__col">
              <div className="lp-pos__role">{AP.t("landing.pos.col2.role")}</div>
              <h3>{AP.t("landing.pos.col2.h")}</h3>
              <p>{AP.t("landing.pos.col2.p")}</p>
            </div>
            <div className="lp-pos__col appril">
              <div className="lp-pos__role">{AP.t("landing.pos.col3.role")}</div>
              <h3>{AP.t("landing.pos.col3.h")}</h3>
              <p>{AP.t("landing.pos.col3.p")}</p>
            </div>
          </div>
        </div>
      </section>

      {/* CTA strip */}
      <section className="lp-cta">
        <div className="container">
          <h2>{AP.t("landing.ctaStrip.h")}</h2>
          <p style={{ marginTop: 14, color: "var(--muted)", maxWidth: "60ch", margin: "14px auto 0" }}>
            {AP.t("landing.ctaStrip.p")}
          </p>
          <button className="btn btn--primary btn--lg" onClick={onStart}>
            {AP.t("common.calcCta")}
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
          </button>
        </div>
      </section>

      <footer className="lp-footer">
        <span>{AP.t("landing.footer.text")} <a href="https://appril.co">Appril</a></span>
        <span className="lp-footer__url">{AP.t("landing.footer.url")}</span>
      </footer>
    </React.Fragment>
  );
}

window.App = App;
ReactDOM.createRoot(document.getElementById("app")).render(<App />);
