// app.jsx — Sendly main app (i18n + live AI + PayPal)

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

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": ["#9B5DE5", "#F15BB5", "#FEE440", "#00BBF9", "#00F5D4"],
  "previewShape": "postcard",
  "showDoodles": true,
  "confettiOnSend": true,
  "fontHeadline": "Bricolage Grotesque",
  "language": "en"
}/*EDITMODE-END*/;

const FONT_HEADLINE_OPTIONS = ["Bricolage Grotesque", "Fraunces", "DM Serif Display", "Space Grotesk"];
const PALETTE_OPTIONS = [
  ["#FF4FA3", "#FFD23F", "#5BE0B8", "#66B6FF", "#7A4DFF"],
  ["#FF6B4A", "#FFCB45", "#F08CB0", "#5BC8B5", "#7A4DFF"],
  ["#E94B8A", "#FF8E3C", "#FFE066", "#3DB5C4", "#5E55E0"],
  ["#9B5DE5", "#F15BB5", "#FEE440", "#00BBF9", "#00F5D4"],
];

function App() {
  const [tw, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const t = useMemo(() => makeT(tw.language), [tw.language]);
  const langInfo = LANGUAGES_15.find(l => l.code === tw.language) || LANGUAGES_15[0];

  // form state
  const [step, setStep] = useState(1);
  const [recipient, setRecipient] = useState("");
  const [family, setFamily] = useState("");
  const [age, setAge] = useState("");
  const [sender, setSender] = useState("");
  const [occasionId, setOccasionId] = useState("birthday");
  const [messageMode, setMessageMode] = useState("ai"); // 'ai' | 'mine' | 'mix'
  const [userText, setUserText] = useState("");
  const [aiText, setAiText] = useState("");
  const [generating, setGenerating] = useState(false);
  const [channel, setChannel] = useState("email");
  const [contact, setContact] = useState("");
  const [delivery, setDelivery] = useState("now");
  const [scheduledFor, setScheduledFor] = useState("");
  const [sent, setSent] = useState(false);
  const [checkingOut, setCheckingOut] = useState(false);

  const occasion = OCCASIONS.find(o => o.id === occasionId);
  const isSolemnMode = occasion && occasion.mood === "solemn";

  /* ---- Document language + direction ---- */
  useEffect(() => {
    document.documentElement.lang = langInfo.code;
    document.documentElement.dir = langInfo.dir;
  }, [langInfo]);

  /* ---- Palette via CSS vars ---- */
  useEffect(() => {
    const [pink, yellow, mint, sky, plum] = tw.palette;
    const root = document.documentElement;
    if (!isSolemnMode) {
      root.style.setProperty("--pink", pink);
      root.style.setProperty("--yellow", yellow);
      root.style.setProperty("--mint", mint);
      root.style.setProperty("--sky", sky);
      root.style.setProperty("--plum", plum);
    } else {
      root.style.removeProperty("--pink");
      root.style.removeProperty("--yellow");
      root.style.removeProperty("--mint");
      root.style.removeProperty("--sky");
      root.style.removeProperty("--plum");
    }
  }, [tw.palette, isSolemnMode]);

  useEffect(() => {
    document.documentElement.style.setProperty("--font-display", `"${tw.fontHeadline}", system-ui, sans-serif`);
  }, [tw.fontHeadline]);

  useEffect(() => {
    document.body.classList.toggle("mode-solemn", !!isSolemnMode);
  }, [isSolemnMode]);

  /* ---- AI message generation via window.claude.complete ---- */
  // Debounced + cancellable: a new run replaces the previous result.
  const generationKey = useRef(0);
  useEffect(() => {
    if (messageMode === "mine") { setAiText(""); return; }
    // Need at least the basics to write a personalised note
    if (!recipient.trim() || !sender.trim()) { setAiText(""); return; }

    const myKey = ++generationKey.current;
    setGenerating(true);

    const timer = setTimeout(async () => {
      try {
        const text = await generateAIMessage({
          occasionId, recipient, family, age, sender,
          langCode: tw.language,
          langLabel: langInfo.label,
          occasionName: t("occ." + occasionId),
        });
        if (myKey === generationKey.current) setAiText(text);
      } finally {
        if (myKey === generationKey.current) setGenerating(false);
      }
    }, 700);

    return () => clearTimeout(timer);
  }, [occasionId, recipient, family, age, sender, messageMode, tw.language]);

  function regenAi() {
    generationKey.current++;
    setAiText("");
    setGenerating(true);
    (async () => {
      const myKey = ++generationKey.current;
      try {
        const text = await generateAIMessage({
          occasionId, recipient, family, age, sender,
          langCode: tw.language,
          langLabel: langInfo.label,
          occasionName: t("occ." + occasionId),
        });
        if (myKey === generationKey.current) setAiText(text);
      } finally {
        if (myKey === generationKey.current) setGenerating(false);
      }
    })();
  }

  const composedBody = useMemo(() => {
    if (messageMode === "mine") return userText;
    if (messageMode === "ai")   return aiText;
    return [userText, aiText].filter(Boolean).join("\n\n— ✦ —\n\n");
  }, [messageMode, userText, aiText]);

  const previewProps = { occasion, recipient, family, sender, body: composedBody, contact, t };

  /* ---- step gating ---- */
  const canAdvance = (() => {
    if (step === 1) return recipient.trim() && sender.trim();
    if (step === 2) return !!occasionId;
    if (step === 3) {
      if (messageMode === "mine") return userText.trim().length > 0;
      if (messageMode === "mix")  return userText.trim().length > 0 || aiText.trim().length > 0;
      return aiText.trim().length > 0;
    }
    if (step === 4) {
      if (channel === "email") return /.+@.+\..+/.test(contact);
      return contact.replace(/\D/g, "").length >= 7;
    }
    return true;
  })();

  function next() { if (canAdvance) setStep(s => Math.min(s + 1, 5)); }
  function back() { setStep(s => Math.max(s - 1, 1)); }

  async function handleStripeCheckout() {
    setCheckingOut(true);
    try {
      const res = await fetch("https://sentwithlove.vip/create-checkout.php", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          to:            contact,
          channel,
          recipientName: [recipient, family].filter(Boolean).join(" "),
          senderName:    sender,
          occasion:      occasion ? t("occ." + occasion.id) : occasionId,
          body:          composedBody,
        }),
      });
      const data = await res.json();
      if (data.url) window.location.href = data.url;
    } catch (err) {
      console.error("[Sendly] Checkout failed:", err);
      setCheckingOut(false);
    }
  }

  function handleReset() {
    setSent(false);
    setStep(1);
    setRecipient(""); setFamily(""); setAge(""); setSender("");
    setOccasionId("birthday");
    setMessageMode("ai"); setUserText(""); setAiText("");
    setChannel("email"); setContact("");
  }

  const stepTitle = t(`step${step}_title`);
  const stepSub   = t(`step${step}_sub`);

  return (
    <React.Fragment>
      <div className="bg-texture" />
      {tw.showDoodles && <Doodles />}
      <Confetti show={sent && tw.confettiOnSend && !isSolemnMode} palette={tw.palette} />

      <div className="shell">
        {/* Top bar */}
        <header className="topbar">
          <a className="logo" href="#"><span className="logo-mark"><span>S</span></span>Sendly</a>
          <div className="topbar-right">
            <div className="chip" title="Language">
              <span>🌍</span>
              <select value={tw.language} onChange={e => setTweak("language", e.target.value)}>
                {LANGUAGES_15.map(l => <option key={l.code} value={l.code}>{l.flag} {l.label}</option>)}
              </select>
            </div>

          </div>
        </header>

        <MusicWidget t={t} />

        {/* Hero */}
        {!sent && (
          <section className="hero">
            <div className="eyebrow"><span>✨</span> {t("eyebrow")}</div>
            <h1>
              {t("hero_send_a")} <span className="wig">{t("hero_happy")}</span><br />
              {t("hero_or")} <span className="wig alt">{t("hero_heartfelt")}</span> {t("hero_note")}<br />
              <span style={{ fontFamily: "var(--font-hand)", color: "var(--plum)", fontWeight: 400 }}>
                {t("hero_seconds")}
              </span>
            </h1>
            <p className="sub">{t("hero_sub")}</p>
            <div className="price-line">
              <span>{t("hero_price_line")}</span>
              <span className="price-pill">€1.99</span>
            </div>
          </section>
        )}

        {/* Composer */}
        {!sent ? (
          <div className="composer">
            <div className="wizard">
              <div className="wizard-head">
                <StepDots step={step} max={5} />
                <div className="wizard-title">
                  {stepTitle}
                  <small>{stepSub}</small>
                </div>
              </div>

              <div className="wizard-body fade-in" key={step}>
                {step === 1 && (
                  <React.Fragment>
                    <div className="field-row">
                      <div>
                        <label className="label">{t("field_recipient")} <span className="req">*</span></label>
                        <input className="input" value={recipient} onChange={e => setRecipient(e.target.value)} placeholder={t("ph_recipient")} />
                      </div>
                      <div>
                        <label className="label">{t("field_family")} <span className="opt">{t("opt")}</span></label>
                        <input className="input" value={family} onChange={e => setFamily(e.target.value)} placeholder={t("ph_family")} />
                      </div>
                    </div>
                    <div className="field-row thin">
                      <div>
                        <label className="label">{t("field_your_name")} <span className="req">*</span></label>
                        <input className="input" value={sender} onChange={e => setSender(e.target.value)} placeholder={t("ph_sender")} />
                      </div>
                      <div>
                        <label className="label">{t("field_age")} <span className="opt">{t("opt")}</span></label>
                        <input className="input" type="number" min="0" max="130" value={age} onChange={e => setAge(e.target.value)} placeholder={t("ph_age")} />
                      </div>
                    </div>
                  </React.Fragment>
                )}

                {step === 2 && (
                  <React.Fragment>
                    <label className="label">{t("field_occasion")} <span className="req">*</span></label>
                    <OccasionGrid value={occasionId} onChange={setOccasionId} t={t} />
                    {isSolemnMode && (
                      <div style={{
                        marginTop: 18,
                        background: "color-mix(in oklch, var(--plum) 12%, var(--paper))",
                        border: "2px solid var(--line)",
                        borderRadius: 14,
                        padding: "12px 14px",
                        fontSize: 13,
                        color: "var(--ink-soft)",
                        lineHeight: 1.5
                      }}>
                        <strong style={{ color: "var(--ink)" }}>{t("condolence_note_strong")}</strong>
                        {t("condolence_note_rest")}
                      </div>
                    )}
                  </React.Fragment>
                )}

                {step === 3 && (
                  <React.Fragment>
                    <label className="label">{t("field_how_write")}</label>
                    <div className="seg" style={{ marginBottom: 18 }}>
                      <button className={"seg-btn" + (messageMode === "ai"   ? " active" : "")} onClick={() => setMessageMode("ai")}>{t("mode_ai")}</button>
                      <button className={"seg-btn" + (messageMode === "mix"  ? " active" : "")} onClick={() => setMessageMode("mix")}>{t("mode_mix")}</button>
                      <button className={"seg-btn" + (messageMode === "mine" ? " active" : "")} onClick={() => setMessageMode("mine")}>{t("mode_mine")}</button>
                    </div>

                    {(messageMode === "mine" || messageMode === "mix") && (
                      <div className="field">
                        <label className="label">{t("field_your_words")} {messageMode === "mine" && <span className="req">*</span>}</label>
                        <textarea className="textarea" value={userText} onChange={e => setUserText(e.target.value)}
                          placeholder={t("ph_your_words")} rows={4} />
                      </div>
                    )}

                    {(messageMode === "ai" || messageMode === "mix") && (
                      <div className="field">
                        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 }}>
                          <label className="label" style={{ marginBottom: 0 }}>
                            {t("field_sendly_draft")} {generating && <span className="opt">{t("generating")}</span>}
                          </label>
                          <button className="btn btn-ghost" style={{ padding: "6px 12px", fontSize: 13 }} onClick={regenAi} type="button" disabled={!recipient.trim() || !sender.trim()}>
                            {t("regenerate")}
                          </button>
                        </div>
                        <textarea className="textarea" value={aiText} onChange={e => setAiText(e.target.value)} rows={7}
                          placeholder={generating ? t("ph_draft_generating") : t("ph_draft_idle")}
                          style={{ marginTop: 6, opacity: generating ? 0.55 : 1, transition: "opacity 0.2s" }} />
                        {(!recipient.trim() || !sender.trim()) && (
                          <div style={{ fontSize: 12, color: "var(--ink-soft)", marginTop: 6, fontStyle: "italic" }}>
                            ↑ Fill the names in step 1 to generate.
                          </div>
                        )}
                      </div>
                    )}
                  </React.Fragment>
                )}

                {step === 4 && (
                  <React.Fragment>
                    <label className="label">{t("send_via")}</label>
                    <div className="channels" style={{ marginBottom: 18 }}>
                      <button className={"channel email" + (channel === "email" ? " selected" : "")} onClick={() => { setChannel("email"); setContact(""); }} type="button">
                        <div className="channel-icon">
                          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="var(--line)" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                            <rect x="3" y="5" width="18" height="14" rx="2" />
                            <path d="m3 7 9 6 9-6" />
                          </svg>
                        </div>
                        <div>
                          <div className="channel-title">{t("email")}</div>
                          <div className="channel-sub">{t("email_sub")}</div>
                        </div>
                      </button>
                      <button className={"channel sms" + (channel === "sms" ? " selected" : "")} onClick={() => { setChannel("sms"); setContact(""); }} type="button">
                        <div className="channel-icon">
                          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="var(--line)" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                            <rect x="6" y="3" width="12" height="18" rx="3" />
                            <line x1="11" y1="18" x2="13" y2="18" />
                          </svg>
                        </div>
                        <div>
                          <div className="channel-title">{t("sms")}</div>
                          <div className="channel-sub">{t("sms_sub")}</div>
                        </div>
                      </button>
                    </div>

                    <div className="field">
                      <label className="label">
                        {channel === "email" ? t("their_email") : t("their_phone")} <span className="req">*</span>
                      </label>
                      <input className="input" value={contact} onChange={e => setContact(e.target.value)}
                        placeholder={channel === "email" ? "name@example.com" : "+1 555 010 2233"}
                        type={channel === "email" ? "email" : "tel"} />
                    </div>

                    <label className="label">{t("deliver")}</label>
                    <div className="seg" style={{ marginBottom: 0 }}>
                      <button className={"seg-btn" + (delivery === "now" ? " active" : "")} onClick={() => setDelivery("now")}>{t("now")}</button>
                      <button className={"seg-btn" + (delivery === "scheduled" ? " active" : "")} onClick={() => setDelivery("scheduled")}>{t("schedule")}</button>
                      <button className="seg-btn" disabled style={{ opacity: 0.4 }}>{t("save_draft")}</button>
                    </div>
                    {delivery === "scheduled" && (
                      <input className="input" type="datetime-local" value={scheduledFor} onChange={e => setScheduledFor(e.target.value)} style={{ marginTop: 12 }} />
                    )}
                  </React.Fragment>
                )}

                {step === 5 && (
                  <React.Fragment>
                    <div className="pay-summary">
                      <div className="pay-summary-left">
                        <strong>{occasion ? t("tag." + occasion.id) : "—"}</strong> · {[recipient, family].filter(Boolean).join(" ") || "—"}
                        <div className="row">
                          {t("via")} {channel === "email" ? t("email").toLowerCase() : t("sms")} · {delivery === "now" ? t("right_away") : t("scheduled")}
                        </div>
                      </div>
                      <div className="pay-total">
                        €1.99
                        <small>~$2.15</small>
                      </div>
                    </div>

                    <button
                      type="button"
                      className="btn primary"
                      onClick={handleStripeCheckout}
                      disabled={checkingOut}
                      style={{ width: "100%", padding: "15px", fontSize: 16, marginTop: 8 }}
                    >
                      {checkingOut ? "Redirecting…" : "Pay €1.99 securely →"}
                    </button>

                    <div style={{ fontSize: 12, color: "var(--ink-soft)", marginTop: 14, lineHeight: 1.5 }}>
                      {t("pay_secure")}
                    </div>
                  </React.Fragment>
                )}
              </div>

              <div className="wizard-foot">
                <button className="btn btn-ghost" onClick={back} disabled={step === 1}>← {t("back")}</button>
                {step < 5 && (
                  <button className="btn primary" onClick={next} disabled={!canAdvance}>
                    {t("continue")} →
                  </button>
                )}
              </div>
            </div>

            {/* RIGHT: preview */}
            <div className="preview-wrap">
              <div className="preview-label">{t("preview_label")}</div>
              {tw.previewShape === "postcard" && <PostcardPreview {...previewProps} />}
              {tw.previewShape === "email"    && <EmailPreview    {...previewProps} />}
              {tw.previewShape === "sms"      && <SmsPreview      {...previewProps} />}
            </div>
          </div>
        ) : (
          <div className="success fade-in" style={{ marginTop: 56 }}>
            <div className="success-check">
              <svg width="50" height="50" viewBox="0 0 50 50" fill="none">
                <path d="M12 26 L22 36 L40 16" stroke="var(--line)" strokeWidth="5" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </div>
            <h2>{isSolemnMode ? t("success_solemn") : t("success_happy")}</h2>
            <p>
              {t("success_msg_pre")}{" "}
              <strong>{delivery === "now" ? t("success_delivered") : t("success_scheduled")}</strong>{" "}
              {t("success_msg_mid")}{" "}
              <strong>{[recipient, family].filter(Boolean).join(" ") || "—"}</strong>{" "}
              {t("success_msg_via")} {channel === "email" ? t("email").toLowerCase() : t("sms")}. {t("success_msg_post")}
            </p>
            <div className="success-actions">
              <button className="btn primary" onClick={handleReset}>{t("send_another")}</button>
              <button className="btn">{t("view_receipt")}</button>
            </div>
          </div>
        )}

        {/* Support row */}
        <div className="support-row">
          <div className="support-tile">
            <div className="support-icon" style={{ background: "var(--yellow)" }}>€</div>
            <h4>{t("tile1_title")}</h4>
            <p>{t("tile1_body")}</p>
          </div>
          <div className="support-tile">
            <div className="support-icon" style={{ background: "var(--mint)" }}>🌍</div>
            <h4>{t("tile2_title")}</h4>
            <p>{t("tile2_body")}</p>
          </div>
          <div className="support-tile">
            <div className="support-icon" style={{ background: "var(--sky)" }}>✨</div>
            <h4>{t("tile3_title")}</h4>
            <p>{t("tile3_body")}</p>
          </div>
          <div className="support-tile">
            <div className="support-icon" style={{ background: "var(--pink)", color: "var(--paper)" }}>♥</div>
            <h4>{t("tile4_title")}</h4>
            <p>{t("tile4_body")}</p>
          </div>
        </div>

        <div className="foot">{t("foot")}</div>
      </div>

      {/* Tweaks */}
      <TweaksPanel>
        <TweakSection label="Language" />
        <TweakSelect label="UI language" value={tw.language}
          options={LANGUAGES_15.map(l => l.code)}
          onChange={v => setTweak("language", v)} />

        <TweakSection label="Look & feel" />
        <TweakColor label="Palette" value={tw.palette} options={PALETTE_OPTIONS}
          onChange={v => setTweak("palette", v)} />
        <TweakSelect label="Headline font" value={tw.fontHeadline} options={FONT_HEADLINE_OPTIONS}
          onChange={v => setTweak("fontHeadline", v)} />
        <TweakToggle label="Background doodles" value={tw.showDoodles}
          onChange={v => setTweak("showDoodles", v)} />

        <TweakSection label="Preview" />
        <TweakRadio label="Shape" value={tw.previewShape}
          options={["postcard", "email", "sms"]}
          onChange={v => setTweak("previewShape", v)} />

        <TweakSection label="Behaviour" />
        <TweakToggle label="Confetti on send" value={tw.confettiOnSend}
          onChange={v => setTweak("confettiOnSend", v)} />
      </TweaksPanel>
    </React.Fragment>
  );
}

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