// Interactive AI form — the conversion moment
const { useState, useEffect, useRef } = React;

const DEFAULT_TARGETS = [
  "Indépendants et freelances",
  "Étudiants et jeunes actifs",
  "PME et petites équipes",
  "Créateurs de contenu"
];

const GEO_OPTIONS = ["France", "Monde entier", "Pas sûr"];
const STAGE_OPTIONS = [
  { key: "ready", label: "App en ligne, personne ne sait", hint: "On t'aide à sortir du silence" },
  { key: "stagnant", label: "Quelques utilisateurs, ça stagne", hint: "On regarde ce qui bloque" },
  { key: "soon", label: "Pas encore publiée", hint: "On prépare le terrain avant la mise en ligne" }
];

const LOADING_STEPS = [
  "On lit ton app…",
  "On identifie qui pourrait être concerné…",
  "On repère où on peut la présenter intelligemment…",
  "On prépare ta première piste d'action…"
];

function ProgressDots({ step, total }) {
  return (
    <div className="form-progress" aria-label={`Étape ${step + 1} sur ${total}`}>
      {Array.from({ length: total }).map((_, i) => (
        <div key={i} className={`form-dot ${i === step ? "active" : i < step ? "done" : ""}`} />
      ))}
    </div>
  );
}

function CloseIcon() {
  return (
    <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
      <path d="M1 1L13 13M13 1L1 13" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
    </svg>
  );
}

function Arrow({ size = 16 }) {
  return (
    <svg className="arrow" width={size} height={size} viewBox="0 0 16 16" fill="none">
      <path d="M2 8H14M14 8L9 3M14 8L9 13" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

function BackArrow() {
  return (
    <svg width="14" height="14" viewBox="0 0 16 16" fill="none">
      <path d="M14 8H2M2 8L7 3M2 8L7 13" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

function StepDescribe({ value, onChange, onNext }) {
  const ref = useRef(null);
  useEffect(() => { ref.current?.focus(); }, []);
  const onKey = (e) => {
    if (e.key === "Enter" && (e.metaKey || e.ctrlKey) && value.trim().length > 5) onNext();
  };
  return (
    <div className="form-step entering">
      <div className="form-stepnum">01 / 04</div>
      <h2 className="form-q">Salut. Raconte-nous ton app <span className="serif">en une phrase.</span></h2>
      <textarea
        ref={ref}
        className="form-textarea"
        placeholder="Ex : une app qui aide les parents à organiser les repas de la semaine."
        value={value}
        onChange={(e) => onChange(e.target.value)}
        onKeyDown={onKey}
        rows={3}
      />
      <div className="form-hint">
        <span>Astuce : sois concret, on s'occupe du reste.</span>
        <span style={{ marginLeft: "auto" }}><span className="kbd">⌘</span> + <span className="kbd">↵</span> pour continuer</span>
      </div>
    </div>
  );
}

function StepTargets({ value, options, loading, onChange, onCustom }) {
  return (
    <div className="form-step entering">
      <div className="form-stepnum">02 / 04</div>
      <h2 className="form-q">Génial. Cette app intéresse plutôt <span className="serif">qui ?</span></h2>
      {loading ? (
        <div className="form-options">
          {[0,1,2,3].map(i => (
            <div key={i} className="form-option" style={{ opacity: .5, pointerEvents: "none" }}>
              <div className="opt-label">
                <div className="opt-dot" />
                <div style={{
                  height: 14, width: 180 + i * 30, background: "var(--bg-tinted)",
                  borderRadius: 4, animation: "pulse-bg 1.4s ease-in-out infinite"
                }} />
              </div>
            </div>
          ))}
          <div style={{ fontSize: 13, color: "var(--fg-muted)", marginTop: 8, display: "flex", alignItems: "center", gap: 8 }}>
            <span style={{
              width: 12, height: 12, border: "1.5px solid var(--accent)", borderTopColor: "transparent",
              borderRadius: "50%", display: "inline-block", animation: "spin .8s linear infinite"
            }} />
            L'IA propose des cibles probables pour ton app…
          </div>
          <style>{`@keyframes pulse-bg { 0%,100% { opacity: 1; } 50% { opacity: .5; } }`}</style>
        </div>
      ) : (
        <div className="form-options">
          {options.map((opt, i) => {
            const selected = value === opt;
            return (
              <button key={opt} className={`form-option ${selected ? "selected" : ""}`} onClick={() => onChange(opt)}>
                <div className="opt-label">
                  <div className="opt-dot" />
                  <span>{opt}</span>
                </div>
                <span className="keynum">{i + 1}</span>
              </button>
            );
          })}
          <button className={`form-option ${value === "__custom" ? "selected" : ""}`} onClick={onCustom}>
            <div className="opt-label">
              <div className="opt-dot" />
              <span style={{ color: "var(--fg-soft)" }}>Autre - je précise</span>
            </div>
            <span className="keynum">5</span>
          </button>
        </div>
      )}
    </div>
  );
}

function StepGeo({ value, onChange }) {
  return (
    <div className="form-step entering">
      <div className="form-stepnum">03 / 04</div>
      <h2 className="form-q">Plutôt en France, dans le monde, <span className="serif">ou tu sais pas encore ?</span></h2>
      <div className="form-pills">
        {GEO_OPTIONS.map(opt => (
          <button key={opt} className={`form-pill ${value === opt ? "selected" : ""}`} onClick={() => onChange(opt)}>
            {opt}
          </button>
        ))}
      </div>
    </div>
  );
}

function StepStage({ value, onChange }) {
  return (
    <div className="form-step entering">
      <div className="form-stepnum">04 / 04</div>
      <h2 className="form-q">Où <span className="serif">t'en es</span> exactement ?</h2>
      <div className="form-options">
        {STAGE_OPTIONS.map((opt, i) => {
          const selected = value === opt.key;
          return (
            <button key={opt.key} className={`form-option ${selected ? "selected" : ""}`} onClick={() => onChange(opt.key)}>
              <div className="opt-label">
                <div className="opt-dot" />
                <span>
                  {opt.label}
                  <span style={{ display: "block", fontSize: 13, color: "var(--fg-muted)", marginTop: 2 }}>{opt.hint}</span>
                </span>
              </div>
              <span className="keynum">{i + 1}</span>
            </button>
          );
        })}
      </div>
    </div>
  );
}

function StepLoading({ onDone }) {
  const [shown, setShown] = useState(0);
  const [done, setDone] = useState(-1);

  useEffect(() => {
    const timers = [];
    LOADING_STEPS.forEach((_, i) => {
      timers.push(setTimeout(() => setShown(i + 1), i * 800 + 200));
      timers.push(setTimeout(() => setDone(i), i * 800 + 900));
    });
    timers.push(setTimeout(onDone, LOADING_STEPS.length * 800 + 600));
    return () => timers.forEach(clearTimeout);
  }, []);

  return (
    <div className="form-step entering">
      <div className="form-stepnum">- ANALYSE EN COURS -</div>
      <h2 className="form-q" style={{ marginBottom: 48 }}>On <span className="serif">prépare</span> ton estimation.</h2>
      <div className="loading-stack">
        {LOADING_STEPS.map((step, i) => (
          <div key={i} className={`loading-line ${i < shown ? "show" : ""} ${i <= done ? "done" : ""}`}>
            <span className="ico" />
            <span>{step}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function StepResult({ result, onActivate, price }) {
  return (
    <div className="form-step entering">
      <div className="result-tag">
        <span className="dot" />
        On a regardé ton app
      </div>
      <div className="result-num">
        {result.low}–{result.high}
      </div>
      <div style={{ fontSize: 14, letterSpacing: 0, textTransform: "none", color: "var(--fg-muted)", marginBottom: 28, fontWeight: 500 }}>
        Personnes potentiellement concernées par ton app, en première estimation
      </div>
      <p className="result-sub">
        D'après ce qu'on lit de ton app, le premier groupe de personnes à toucher se trouve probablement parmi <strong>{result.audience}</strong>{result.geo ? ` ${result.geo}` : ""}, qu'on peut atteindre via {result.channels}.
        {" "}
        On a une première piste d'action concrète à te proposer. <strong>On démarre l'étape d'après ?</strong>
      </p>
      <div className="result-card">
        <div className="result-stat">
          <div className="lbl">Cible</div>
          <div className="val">{result.audience}</div>
        </div>
        <div className="result-stat">
          <div className="lbl">Zone</div>
          <div className="val">{result.geo || "-"}</div>
        </div>
        <div className="result-stat">
          <div className="lbl">Canaux prioritaires</div>
          <div className="val">{result.channels}</div>
        </div>
      </div>
      <div className="result-cta">
        <button className="btn-primary big" onClick={onActivate}>
          Démarrer l'étape d'après - {price}
          <Arrow />
        </button>
        <span className="result-meta">Paiement sécurisé · Remboursé si aucune action lancée sous 7 jours</span>
      </div>
    </div>
  );
}

function StepPaid({ onClose }) {
  return (
    <div className="form-step entering" style={{ textAlign: "center" }}>
      <div style={{
        width: 84, height: 84, borderRadius: "50%", background: "var(--primary)",
        margin: "0 auto 32px", display: "flex", alignItems: "center", justifyContent: "center",
        boxShadow: "0 12px 30px rgba(26,86,219,.3)"
      }}>
        <svg width="36" height="36" viewBox="0 0 24 24" fill="none">
          <path d="M5 12.5L10 17.5L19 7.5" stroke="white" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
      </div>
      <h2 className="form-q" style={{ textAlign: "center", margin: "0 auto 20px", maxWidth: "16ch" }}>
        C'est <span className="serif">lancé.</span>
      </h2>
      <p className="result-sub" style={{ margin: "0 auto 36px", textAlign: "center" }}>
        On a reçu ton brief. Tu recevras un récap par email dans les minutes qui suivent, et une première analyse claire <strong>sous 48h</strong>.
      </p>
      <button className="btn-ghost" onClick={onClose}>Retour à l'accueil</button>
    </div>
  );
}

// ---- Claude integration ----
async function generateTargets(appDescription) {
  try {
    const prompt = `Tu es un assistant marketing. Pour cette app, propose 4 segments d'utilisateurs cibles plausibles et précis (pas génériques). Chaque segment doit faire entre 4 et 7 mots, en français.

App : "${appDescription}"

Réponds UNIQUEMENT avec un JSON array de 4 strings, rien d'autre. Exemple : ["Parents de jeunes enfants 30-45 ans", "Couples qui cuisinent ensemble", "..."]`;
    const out = await window.claude.complete(prompt);
    const cleaned = out.replace(/```json|```/g, "").trim();
    const match = cleaned.match(/\[[\s\S]*\]/);
    if (!match) throw new Error("no array");
    const arr = JSON.parse(match[0]);
    if (Array.isArray(arr) && arr.length >= 3) return arr.slice(0, 4);
    throw new Error("bad array");
  } catch (e) {
    console.warn("Target generation fallback", e);
    return DEFAULT_TARGETS;
  }
}

async function generateEstimate({ desc, audience, geo, stage }) {
  // Always produce a number in 200-800 range
  const seed = (desc + audience + geo + stage).split("").reduce((a, c) => a + c.charCodeAt(0), 0);
  const base = 220 + (seed % 380);
  const spread = 80 + (seed % 140);
  const low = base;
  const high = base + spread;

  let channels = "Instagram et communautés Reddit";
  try {
    const prompt = `Pour cette app et cette audience, suggère 2 canaux d'acquisition concrets (réseaux sociaux, forums, communautés). Réponds avec une seule phrase courte en français, format : "X et Y".

App : "${desc}"
Audience : ${audience}
Zone : ${geo}

Exemple : "Instagram et groupes Facebook parentalité" — ne dépasse pas 10 mots, pas de guillemets, pas de point final.`;
    const out = await window.claude.complete(prompt);
    const trimmed = out.trim().replace(/^["']|["']$/g, "").replace(/\.$/, "").split("\n")[0];
    if (trimmed && trimmed.length < 90) channels = trimmed;
  } catch (e) {
    console.warn("Channels fallback", e);
  }

  return {
    low, high,
    audience: audience === "__custom" ? "ta cible spécifique" : audience,
    geo: geo === "Pas sûr" ? "" : (geo === "France" ? "en France" : "à l'international"),
    channels
  };
}

function InteractiveForm({ onClose, price, onPaid, initialDesc = "" }) {
  const hasInitial = initialDesc.trim().length > 5;
  const [step, setStep] = useState(hasInitial ? 1 : 0);
  const [desc, setDesc] = useState(initialDesc);
  const [targets, setTargets] = useState(DEFAULT_TARGETS);
  const [targetsLoading, setTargetsLoading] = useState(hasInitial);
  const [audience, setAudience] = useState("");
  const [customAudience, setCustomAudience] = useState("");
  const [geo, setGeo] = useState("");
  const [stage, setStage] = useState("");
  const [result, setResult] = useState(null);
  const [paid, setPaid] = useState(false);

  const advance = () => setStep(s => s + 1);
  const back = () => setStep(s => Math.max(0, s - 1));

  // Escape closes
  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose]);

  // Pre-filled hero description → kick off AI target generation immediately.
  useEffect(() => {
    if (!hasInitial) return;
    let cancelled = false;
    (async () => {
      const t = await generateTargets(initialDesc);
      if (!cancelled) { setTargets(t); setTargetsLoading(false); }
    })();
    return () => { cancelled = true; };
  }, []);

  // Trigger AI targets after step 0
  const goToTargets = async () => {
    advance();
    setTargetsLoading(true);
    const t = await generateTargets(desc);
    setTargets(t);
    setTargetsLoading(false);
  };

  // Loading -> result
  const onLoadingDone = async () => {
    const finalAudience = audience === "__custom" ? (customAudience || "ta cible spécifique") : audience;
    const r = await generateEstimate({ desc, audience: finalAudience, geo, stage });
    setResult(r);
    setStep(5);
  };

  const onActivate = () => {
    setPaid(true);
    onPaid?.();
  };

  const stepsForProgress = 5; // 4 questions + loading; result is a reveal

  let body;
  if (paid) {
    body = <StepPaid onClose={onClose} />;
  } else if (step === 0) {
    body = (
      <StepDescribe
        value={desc}
        onChange={setDesc}
        onNext={goToTargets}
      />
    );
  } else if (step === 1) {
    body = (
      <StepTargets
        value={audience}
        options={targets}
        loading={targetsLoading}
        onChange={(v) => setAudience(v)}
        onCustom={() => setAudience("__custom")}
      />
    );
  } else if (step === 2) {
    body = <StepGeo value={geo} onChange={setGeo} />;
  } else if (step === 3) {
    body = <StepStage value={stage} onChange={setStage} />;
  } else if (step === 4) {
    body = <StepLoading onDone={onLoadingDone} />;
  } else if (step === 5 && result) {
    body = <StepResult result={result} onActivate={onActivate} price={price} />;
  }

  // Determine if "next" is enabled
  const canAdvance = (() => {
    if (step === 0) return desc.trim().length > 5;
    if (step === 1) return audience && audience !== "__custom";
    if (step === 2) return !!geo;
    if (step === 3) return !!stage;
    return false;
  })();

  const showActions = !paid && step < 4;
  const showNext = step < 4;

  const onNextClick = () => {
    if (step === 0) { goToTargets(); return; }
    if (step === 3) { setStep(4); return; }
    advance();
  };

  return (
    <div className="form-overlay" role="dialog" aria-modal="true">
      <div className="form-top">
        <div className="brand">
          <img src="logo.png" alt="Après Lancement" className="brand-logo" />
          <span>Après Lancement</span>
        </div>
        {!paid && step < 5 && <ProgressDots step={Math.min(step, stepsForProgress - 1)} total={stepsForProgress} />}
        <button className="form-close" onClick={onClose} aria-label="Fermer">
          <CloseIcon />
        </button>
      </div>
      <div className="form-body">
        {body}
      </div>
      {showActions && (
        <div style={{ borderTop: "1px solid var(--line)", padding: "20px 32px" }}>
          <div style={{ maxWidth: 720, margin: "0 auto" }} className="form-actions" >
            {step > 0 ? (
              <button className="form-back" onClick={back}>
                <BackArrow /> Précédent
              </button>
            ) : <span style={{ fontSize: 13, color: "var(--fg-muted)" }}>Aucune carte requise.</span>}
            {showNext && (
              <button className="form-next" disabled={!canAdvance} onClick={onNextClick}>
                Continuer <Arrow />
              </button>
            )}
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { InteractiveForm, Arrow, BackArrow, CloseIcon });
