/* Birth Energy Reading — mobile-first landing page
   Components + interactivity. Loaded via Babel after tweaks-panel.jsx */

const { useState, useEffect, useMemo, useRef } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "ctaColor": "#F4502E",
  "headingFont": "Playfair Display",
  "starDensity": 110,
  "showPromoBar": true
}/*EDITMODE-END*/;

/* ---------- tokens ---------- */
const T = {
  ink: "#0A1713",          // deep ink green / near black
  ink2: "#0E1F1A",
  panel: "#0C1B16",
  cream: "#F7F1E1",
  creamDim: "rgba(247,241,225,0.72)",
  creamFaint: "rgba(247,241,225,0.45)",
  gold: "#E3C36C",
  goldDeep: "#C9A648",
  line: "rgba(227,195,108,0.22)",
};

function ctaGradient(c) {
  return `linear-gradient(135deg, ${c} 0%, color-mix(in oklch, ${c} 72%, #ffb35c) 100%)`;
}

/* ---------- starfield ---------- */
function Starfield({ density }) {
  const stars = useMemo(() => {
    const rng = mulberry32(7);
    return Array.from({ length: density }, (_, i) => ({
      x: rng() * 100,
      y: rng() * 100,
      s: rng() < 0.85 ? 1 : 2,
      o: 0.25 + rng() * 0.55,
      d: 2.5 + rng() * 4,
      delay: rng() * 5,
    }));
  }, [density]);
  return (
    <div className="starfield" aria-hidden="true">
      {stars.map((st, i) => (
        <span
          key={i}
          className="star"
          style={{
            left: st.x + "%",
            top: st.y + "%",
            width: st.s + "px",
            height: st.s + "px",
            opacity: st.o,
            animationDuration: st.d + "s",
            animationDelay: st.delay + "s",
          }}
        ></span>
      ))}
    </div>
  );
}
function mulberry32(a) {
  return function () {
    a |= 0; a = (a + 0x6d2b79f5) | 0;
    let t = Math.imul(a ^ (a >>> 15), 1 | a);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

/* ---------- astro wheel (simple geometry only) ---------- */
function AstroWheel({ size = 300, faded = false }) {
  const c = size / 2;
  const rings = [0.98, 0.78, 0.58, 0.38, 0.2];
  const spokes = 12;
  const stroke = faded ? "rgba(227,195,108,0.55)" : T.gold;
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} fill="none" aria-hidden="true">
      {rings.map((r, i) => (
        <circle key={i} cx={c} cy={c} r={c * r - 1} stroke={stroke} strokeWidth={i === 0 ? 1.4 : 0.8} opacity={i === 0 ? 0.9 : 0.55}></circle>
      ))}
      {Array.from({ length: spokes }, (_, i) => {
        const a = (i / spokes) * Math.PI * 2;
        const r1 = c * 0.2, r2 = c * 0.98 - 1;
        return (
          <line
            key={i}
            x1={c + Math.cos(a) * r1} y1={c + Math.sin(a) * r1}
            x2={c + Math.cos(a) * r2} y2={c + Math.sin(a) * r2}
            stroke={stroke} strokeWidth="0.7" opacity="0.45"
          ></line>
        );
      })}
      {/* tick dots on outer ring */}
      {Array.from({ length: 24 }, (_, i) => {
        const a = (i / 24) * Math.PI * 2;
        const r = c * 0.88;
        return <circle key={"d" + i} cx={c + Math.cos(a) * r} cy={c + Math.sin(a) * r} r="1.3" fill={stroke} opacity="0.5"></circle>;
      })}
      <circle cx={c} cy={c} r={c * 0.07} stroke={stroke} strokeWidth="1.6" opacity="0.9"></circle>
    </svg>
  );
}

function MoonMark({ size = 22 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" aria-hidden="true">
      <circle cx="12" cy="12" r="10" fill={T.gold}></circle>
      <circle cx="16" cy="10" r="8.5" fill={T.ink}></circle>
    </svg>
  );
}

/* ---------- small bits ---------- */
function Pill({ children, tone = "gold" }) {
  return <span className={"pill pill-" + tone}>{children}</span>;
}

/* ---------- form ---------- */
const CLARITY = ["Love", "Money", "Career", "Wellness", "Family", "Other"];

function Field({ label, hint, children }) {
  return (
    <label className="field">
      <span className="field-label">
        {label}
        {hint ? <span className="field-hint">{hint}</span> : null}
      </span>
      {children}
    </label>
  );
}

function ReadingForm({ ctaColor }) {
  const [form, setForm] = useState({ date: "", time: "", place: "", gender: "", email: "", whatsapp: "" });
  const [areas, setAreas] = useState([]);
  const [otherArea, setOtherArea] = useState("");
  const [touched, setTouched] = useState(false);
  const [sent, setSent] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState("");
  const today = new Date().toISOString().slice(0, 10);

  const emailOk = !form.email.trim() || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email);
  const whatsappOk = form.whatsapp.trim().length > 0;
  const dateOk = form.date.trim().length > 0;
  const valid = emailOk && whatsappOk && dateOk;

  const set = (k) => (e) => setForm({ ...form, [k]: e.target.value });
  const toggleArea = (a) => {
    if (areas.includes(a)) {
      setAreas(areas.filter((x) => x !== a));
      if (a === "Other") setOtherArea("");
    } else {
      setAreas([...areas, a]);
    }
  };

  const submit = async (e) => {
    e.preventDefault();
    setTouched(true);
    setSubmitError("");
    if (!valid || submitting) return;

    setSubmitting(true);
    try {
      const response = await fetch("api/readings", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          ...form,
          areas,
          otherArea,
          userAgent: navigator.userAgent,
        }),
      });
      const result = await response.json().catch(() => ({}));
      if (!response.ok || !result.ok) {
        throw new Error(result.error || "Could not save your reading request.");
      }
      setSent(true);
    } catch (error) {
      setSubmitError(error.message || "Could not save your reading request.");
    } finally {
      setSubmitting(false);
    }
  };

  if (sent) {
    return (
      <div className="form-card form-success" id="claim-form">
        <MoonMark size={30}></MoonMark>
        <h3 className="form-title" style={{ marginTop: 14 }}>Your reading is on its way</h3>
        <p className="form-sub" style={{ marginBottom: 4 }}>
          We'll prepare your personalized reading and send it to WhatsApp <strong>{form.whatsapp}</strong> within 24 hours.
          {form.email ? " We'll also keep your email on file as a backup contact." : ""}
        </p>
        <button type="button" className="link-btn" onClick={() => setSent(false)}>Edit my details</button>
      </div>
    );
  }

  return (
    <form className="form-card" id="claim-form" onSubmit={submit} noValidate>
      <h3 className="form-title">Claim your free reading</h3>
      <p className="form-sub">WhatsApp is required so we can deliver your reading quickly.</p>

      <div className="form-grid">
        <Field label="Birth date">
          <input
            className={"input date-input" + (touched && !dateOk ? " input-error" : "")}
            type="date"
            max={today}
            aria-label="Birth date"
            value={form.date} onChange={set("date")}
          ></input>
        </Field>
        <Field label="Birth time">
          <input className="input" placeholder="Optional" value={form.time} onChange={set("time")}></input>
        </Field>
        <Field label="Birthplace">
          <input className="input" placeholder="City / Country" value={form.place} onChange={set("place")}></input>
        </Field>
        <Field label="Gender">
          <input className="input" placeholder="Optional" value={form.gender} onChange={set("gender")}></input>
        </Field>
      </div>

      <div className="form-grid">
        <Field label="Email address">
          <input
            className={"input" + (touched && !emailOk ? " input-error" : "")}
            placeholder="name@email.com"
            type="email"
            value={form.email}
            onChange={set("email")}
          ></input>
        </Field>
        <Field label="WhatsApp" hint={<span className="tag-main">Main</span>}>
          <input
            className={"input input-main" + (touched && !whatsappOk ? " input-error" : "")}
            placeholder="WhatsApp number"
            inputMode="tel"
            value={form.whatsapp}
            onChange={set("whatsapp")}
          ></input>
        </Field>
      </div>
      {touched && !valid ? (
        <p className="form-error" role="alert">
          {!emailOk ? "Please enter a valid email address. " : ""}
          {!whatsappOk ? "Please add your WhatsApp number. " : ""}
          {!dateOk ? "Please add your birth date." : ""}
        </p>
      ) : null}
      {submitError ? <p className="form-error" role="alert">{submitError}</p> : null}

      <div className="clarity">
        <span className="field-label">What do you want clarity on?</span>
        <div className="clarity-chips">
          {CLARITY.map((a) => (
            <button
              type="button" key={a}
              className={"chip" + (areas.includes(a) ? " chip-on" : "")}
              aria-pressed={areas.includes(a)}
              onClick={() => toggleArea(a)}
            >{a}</button>
          ))}
        </div>
        {areas.includes("Other") ? (
          <input
            className="input other-input"
            placeholder="Tell us what you want clarity on"
            value={otherArea}
            onChange={(e) => setOtherArea(e.target.value)}
            aria-label="Other clarity topic"
          ></input>
        ) : null}
      </div>

      <button type="submit" className="cta cta-block" style={{ background: ctaGradient(ctaColor) }} disabled={submitting}>
        {submitting ? "Saving..." : "Get My Free Personalized Reading"}
      </button>

      <p className="trust-line" style={{ color: ctaColor }}>No payment · No card · WhatsApp delivery · Sent within 24h</p>
      <p className="disclaimer">
        By submitting, you agree to receive this reading by the contact method you provide. We do not publicly share your details.
      </p>
    </form>
  );
}

/* ---------- preview section ---------- */
const PREVIEW_ITEMS = [
  { k: "L", color: "#D8456B", name: "Love", q: "Why are they hot and cold?", d: "relationship rhythm, boundaries, next move" },
  { k: "M", color: "#D9A23B", name: "Money", q: "Why does money slip away?", d: "spending patterns, pressure points" },
  { k: "C", color: "#3E7BC6", name: "Career", q: "Should I move or stay?", d: "timing, strengths, next priority" },
  { k: "W", color: "#2E9A6B", name: "Wellness", q: "Why do I feel drained?", d: "energy patterns, rest, emotional balance" },
  { k: "F", color: "#8A5BC6", name: "Family", q: "How do I handle pressure?", d: "communication, boundaries, family roles" },
  { k: "O", color: "#9AA2A6", name: "Other", q: "What direction feels right?", d: "life direction, stuck points, next step" },
];

function PreviewCard() {
  return (
    <div className="preview-card">
      <div className="preview-head">
        <div className="preview-head-text">
          <Pill tone="gold">Preview</Pill>
          <h3 className="preview-title">What your reading can explore</h3>
          <p className="preview-sub">Pick the area you care about most.</p>
        </div>
        <div className="preview-wheel"><AstroWheel size={64} faded={true}></AstroWheel></div>
      </div>
      <div className="preview-grid">
        {PREVIEW_ITEMS.map((it) => (
          <div className="preview-item" key={it.name}>
            <span className="preview-dot" style={{ background: it.color }}>{it.k}</span>
            <div className="preview-item-body">
              <span className="preview-item-name">{it.name}</span>
              <span className="preview-item-q">{it.q}</span>
              <span className="preview-item-d">{it.d}</span>
            </div>
          </div>
        ))}
      </div>
      <div className="takeaways">
        <span className="takeaways-title">Practical takeaways</span>
        <span className="takeaways-body">
          Communication cues, money boundaries, rest rhythm, priority list, lucky color, and a small daily ritual.
        </span>
      </div>
    </div>
  );
}

/* ---------- trust section ---------- */
const TRUST = [
  { k: "F", color: "#C73B5B", title: "Free to start", body: "No payment, no card, and no hidden checkout step for the introductory reading." },
  { k: "P", color: "#2E9A6B", title: "Private by default", body: "Your birth details are used to prepare this reading and are not shown publicly." },
  { k: "S", color: "#3E7BC6", title: "Self-reflection only", body: "A cultural and personal insight guide, not medical, legal, financial, or mental health advice." },
];

/* ---------- app ---------- */
function App() {
  const [localTweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [remoteTweaks, setRemoteTweaks] = useState(null);

  useEffect(() => {
    let cancelled = false;
    fetch("api/settings")
      .then((response) => response.ok ? response.json() : null)
      .then((result) => {
        if (!cancelled && result?.ok && result.settings) {
          setRemoteTweaks(result.settings);
        }
      })
      .catch(() => {});
    return () => {
      cancelled = true;
    };
  }, []);

  const t = remoteTweaks ? { ...localTweaks, ...remoteTweaks } : localTweaks;

  const scrollToForm = () => {
    const el = document.getElementById("claim-form");
    if (el) {
      const y = el.getBoundingClientRect().top + window.scrollY - 24;
      window.scrollTo({ top: y, behavior: "smooth" });
    }
  };

  const headingStack = `'${t.headingFont}', Georgia, serif`;

  return (
    <div className="page" style={{ "--heading-font": headingStack, "--cta": t.ctaColor }}>
      <Starfield density={t.starDensity}></Starfield>

      {t.showPromoBar ? (
        <div className="promo-bar" data-screen-label="Promo bar">
          Limited-time free personalized reading · No payment required
        </div>
      ) : null}

      <header className="header" data-screen-label="Header">
        <div className="brand">
          <MoonMark size={26}></MoonMark>
          <div className="brand-text">
            <span className="brand-name">Birth Energy Reading</span>
            <span className="brand-sub">Personalized self-reflection guide</span>
          </div>
        </div>
        <button type="button" className="header-cta" onClick={scrollToForm}>Free intro reading</button>
      </header>

      <div className="intro-layout">
        <section className="hero" data-screen-label="Hero">
          <div className="hero-wheel" aria-hidden="true">
            <AstroWheel size={320}></AstroWheel>
            <div className="hero-moon">
              <svg width="74" height="74" viewBox="0 0 74 74">
                <circle cx="37" cy="37" r="30" fill={T.gold}></circle>
                <circle cx="48" cy="31" r="26" fill={T.ink}></circle>
              </svg>
            </div>
          </div>

          <div className="hero-tags">
            <Pill tone="gold">Love · Money · Career</Pill>
            <Pill tone="gold">Wellness · Family</Pill>
          </div>

          <h1 className="hero-title">
            <span className="hero-title-top">Get Your Free</span>
            <span className="hero-title-main">Birth Energy Reading</span>
          </h1>

          <p className="hero-copy">
            A personalized self-reflection reading based on your birth details. Explore love,
            money patterns, career direction, wellness, family, and your next step.
          </p>

          <div className="hero-actions">
            <button type="button" className="cta" style={{ background: ctaGradient(t.ctaColor) }} onClick={scrollToForm}>
              Get My Free Reading
            </button>
            <div className="limited-card">
              <span className="limited-label">Limited</span>
              <span className="limited-free" style={{ color: t.ctaColor }}>FREE</span>
              <span className="limited-note" style={{ background: t.ctaColor }}>No card needed</span>
            </div>
          </div>

          <div className="hero-chips">
            {["No payment", "No card", "24h delivery", "WhatsApp delivery"].map((c) => (
              <span className="hero-chip" key={c}>{c}</span>
            ))}
          </div>
        </section>

        <section className="section form-section" data-screen-label="Form">
          <ReadingForm ctaColor={t.ctaColor}></ReadingForm>
        </section>
      </div>

      <section className="section preview-section" data-screen-label="Reading preview">
        <div className="section-copy">
          <h2 className="section-title">A reading that feels specific</h2>
          <p className="section-sub">
            Choose the area you care about most. Your reading turns birth details into clear
            prompts and practical takeaways.
          </p>
        </div>
        <PreviewCard></PreviewCard>
      </section>

      <section className="section trust-section" data-screen-label="Trust">
        <h2 className="section-title">Why it feels easy to try</h2>
        <div className="trust-list">
          {TRUST.map((it) => (
            <div className="trust-card" key={it.title}>
              <span className="trust-dot" style={{ background: it.color }}>{it.k}</span>
              <div className="trust-body">
                <span className="trust-title">{it.title}</span>
                <span className="trust-text">{it.body}</span>
              </div>
            </div>
          ))}
        </div>
      </section>

      <footer className="footer" data-screen-label="Footer">
        <div className="footer-row">
          <div className="footer-text">
            <span className="footer-title">Free intro reading</span>
            <span className="footer-sub">WhatsApp delivery · Sent within 24h</span>
          </div>
          <button type="button" className="cta cta-sm" style={{ background: ctaGradient(t.ctaColor) }} onClick={scrollToForm}>
            Get Free Reading
          </button>
        </div>
        <p className="footer-disclaimer">
          For entertainment and self-reflection only. Not medical, legal, financial, or mental health advice.
        </p>
      </footer>

      <TweaksPanel>
        <TweakSection label="Brand"></TweakSection>
        <TweakColor label="CTA color" value={t.ctaColor}
          options={["#F4502E", "#E03A52", "#C9A648", "#2E9A6B"]}
          onChange={(v) => setTweak("ctaColor", v)}></TweakColor>
        <TweakSelect label="Heading font" value={t.headingFont}
          options={["Playfair Display", "Cormorant Garamond", "EB Garamond"]}
          onChange={(v) => setTweak("headingFont", v)}></TweakSelect>
        <TweakSection label="Atmosphere"></TweakSection>
        <TweakSlider label="Star density" value={t.starDensity} min={0} max={300} step={10}
          onChange={(v) => setTweak("starDensity", v)}></TweakSlider>
        <TweakToggle label="Promo bar" value={t.showPromoBar}
          onChange={(v) => setTweak("showPromoBar", v)}></TweakToggle>
      </TweaksPanel>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App></App>);
