/* =====================================================================
   MODULES — interactive widgets
   Hook Generator · Script Builder · Viral Score · Niche Finder · Quiz
===================================================================== */

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

/* --------------------------------------------------------------------
   HOOK GENERATOR
-------------------------------------------------------------------- */
function HookGenerator() {
  const [idx, setIdx] = useState(0);
  const [filter, setFilter] = useState("All");
  const [rolling, setRolling] = useState(false);

  const filtered = useMemo(
    () => filter === "All" ? HOOKS : HOOKS.filter(h => h.type === filter),
    [filter]
  );

  const safe = ((idx % filtered.length) + filtered.length) % filtered.length;
  const hook = filtered[safe];

  const roll = () => {
    setRolling(true);
    let step = 0;
    const total = 8 + Math.floor(Math.random() * 5);
    const tick = () => {
      step++;
      setIdx(i => i + 1);
      if (step < total) setTimeout(tick, 50 + step * 10);
      else setRolling(false);
    };
    tick();
  };

  return (
    <div className="widget">
      <div className="widget-head">
        <div>
          <div className="widget-label">HOOK GENERATOR</div>
          <div className="widget-title">Tap to roll through proven hooks.</div>
        </div>
        <div className="seg">
          {["All", "Verbal", "Written", "Visual"].map(t => (
            <button
              key={t}
              className={"seg-btn " + (filter === t ? "is-on" : "")}
              onClick={() => setFilter(t)}
            >{t}</button>
          ))}
        </div>
      </div>

      <div className={"hook-card " + (rolling ? "is-rolling" : "")}>
        <div className="hook-card-top">
          <span className={"tag tag-" + (hook.type === "Verbal" ? "accent" : hook.type === "Written" ? "hot" : "green")}>
            {hook.type} Hook
          </span>
          <span className="mono hook-card-num">#{String(safe + 1).padStart(2, "0")} / {String(filtered.length).padStart(2, "0")}</span>
        </div>
        <div className="hook-card-template">{hook.text}</div>
        <div className="hook-card-ex">
          <span className="label" style={{marginBottom: 6}}>Example</span>
          {hook.ex}
        </div>
      </div>

      <div className="row" style={{marginTop: 20, justifyContent: "space-between"}}>
        <button className="btn btn-ghost" onClick={() => setIdx(i => i - 1)}>← Previous</button>
        <button className="btn btn-primary" onClick={roll}>
          <span className="btn-arrow">⚂</span> Roll a new hook
        </button>
        <button className="btn btn-ghost" onClick={() => setIdx(i => i + 1)}>Next →</button>
      </div>
    </div>
  );
}

/* --------------------------------------------------------------------
   SCRIPT BUILDER — fill in the blanks, get a viral script
-------------------------------------------------------------------- */
const SCRIPT_TEMPLATES = [
  {
    name: "The 3 Levels",
    fields: [
      { k: "topic", label: "Topic (1-2 words)", ph: "e.g. Instagram hooks" },
      { k: "bad", label: "What a BAD one looks like", ph: "e.g. 'Here's 5 tips…'" },
      { k: "good", label: "What a GOOD one looks like", ph: "e.g. 'Did you know…'" },
      { k: "best", label: "What the BEST one looks like", ph: "e.g. 'Smart vs dumb creator…'" },
    ],
    build: (v) =>
`HOOK (verbal): 3 levels of ${v.topic || "__topic__"}.
WRITTEN: 3 levels of ${v.topic || "__topic__"} — bad, good, best.
VISUAL: Three tiers on screen, label each one as you say it.

BEAT 1 — LEVEL 1 (BAD)
"Level 1: ${v.bad || "__bad example__"}. This is what most people do — and why most people stay stuck."

BEAT 2 — LEVEL 2 (GOOD)
"Level 2: ${v.good || "__good example__"}. Better — but still missing the real move."

BEAT 3 — LEVEL 3 (BEST)
"Level 3: ${v.best || "__best example__"}. This is what actually moves the needle."

CTA
"Save this so you don't forget. Follow for more ${v.topic || "__topic__"} breakdowns."`
  },
  {
    name: "The Transformation",
    fields: [
      { k: "start", label: "Starting point (number or status)", ph: "e.g. 2 followers" },
      { k: "end", label: "Ending point", ph: "e.g. 30,000 followers" },
      { k: "time", label: "Time frame", ph: "e.g. 25 days" },
      { k: "unlock", label: "The ONE thing that unlocked it", ph: "e.g. gamifying reels" },
    ],
    build: (v) =>
`HOOK (verbal): How I took someone from ${v.start || "__start__"} to ${v.end || "__end__"} in ${v.time || "__time__"}.
WRITTEN: ${v.start || "__start__"} → ${v.end || "__end__"}. No ads. No luck.
VISUAL: Split screen — analytics dashboard before + after.

BEAT 1 — STAKES
"When we started, they had ${v.start || "__start__"}. Most people would've quit."

BEAT 2 — THE UNLOCK
"The one thing that changed everything? ${v.unlock || "__the unlock__"}. Here's exactly how it works…"

BEAT 3 — PROOF
"In ${v.time || "__time__"}, we hit ${v.end || "__end__"}. No paid ads. No viral luck. Just this."

CTA
"DM me 'GROWTH' and I'll send you the framework."`
  },
  {
    name: "The Myth Bust",
    fields: [
      { k: "myth", label: "The myth everyone believes", ph: "e.g. you need to post daily" },
      { k: "truth", label: "The real truth", ph: "e.g. 3 great reels > 30 okay ones" },
      { k: "proof", label: "A specific piece of proof", ph: "e.g. my client posts 4x/week and hit 30K" },
      { k: "do", label: "What they should do instead", ph: "e.g. batch Sundays, post Mon/Wed/Fri/Sat" },
    ],
    build: (v) =>
`HOOK (verbal): Everyone tells you ${v.myth || "__myth__"}. They're wrong.
WRITTEN: The ${v.myth ? v.myth + " " : ""}myth — busted.
VISUAL: Open with a big "WRONG" stamp over a common piece of advice.

BEAT 1 — THE MYTH
"If you've ever been told ${v.myth || "__myth__"} — this video is for you."

BEAT 2 — THE TRUTH
"The truth is: ${v.truth || "__truth__"}."

BEAT 3 — THE PROOF
"${v.proof || "__proof__"}."

BEAT 4 — THE ACTION
"Instead, ${v.do || "__the new action__"}. Screenshot this."

CTA
"Follow for more — I break down one growth myth every week."`
  },
];

function ScriptBuilder() {
  const [tIdx, setTIdx] = useState(0);
  const [values, setValues] = useState({});
  const [copied, setCopied] = useState(false);
  const t = SCRIPT_TEMPLATES[tIdx];
  const script = t.build(values);

  const copy = async () => {
    try {
      await navigator.clipboard.writeText(script);
      setCopied(true);
      setTimeout(() => setCopied(false), 1600);
    } catch (e) {}
  };

  return (
    <div className="widget">
      <div className="widget-head">
        <div>
          <div className="widget-label">SCRIPT BUILDER</div>
          <div className="widget-title">Fill in the blanks. Get a viral script.</div>
        </div>
        <div className="seg">
          {SCRIPT_TEMPLATES.map((s, i) => (
            <button
              key={s.name}
              className={"seg-btn " + (i === tIdx ? "is-on" : "")}
              onClick={() => { setTIdx(i); setValues({}); }}
            >{s.name}</button>
          ))}
        </div>
      </div>

      <div className="builder-grid">
        <div className="builder-inputs">
          {t.fields.map(f => (
            <div key={f.k} className="field">
              <label className="label">{f.label}</label>
              <input
                type="text"
                placeholder={f.ph}
                value={values[f.k] || ""}
                onChange={e => setValues(v => ({ ...v, [f.k]: e.target.value }))}
              />
            </div>
          ))}
        </div>

        <div className="builder-output">
          <div className="row-between" style={{marginBottom: 10}}>
            <span className="label" style={{margin: 0}}>Your Script</span>
            <button className="btn-mini" onClick={copy}>
              {copied ? "✓ Copied" : "Copy script"}
            </button>
          </div>
          <pre className="script-box">{script}</pre>
        </div>
      </div>
    </div>
  );
}

/* --------------------------------------------------------------------
   VIRAL SCORE CALCULATOR
-------------------------------------------------------------------- */
const SCORE_QUESTIONS = [
  { k: "hookV", label: "Does the first 3 seconds have a VERBAL hook?", w: 18 },
  { k: "hookW", label: "Does it have a WRITTEN (on-screen text) hook?", w: 15 },
  { k: "hookVi", label: "Does it have a VISUAL hook — something happening on screen?", w: 15 },
  { k: "outlier", label: "Is the hook based on a proven 5X viral outlier?", w: 14 },
  { k: "value", label: "Is the value measurable and specific (not fluffy)?", w: 12 },
  { k: "format", label: "Does it use an engaging format (not just static talking head)?", w: 10 },
  { k: "length", label: "Is it under 60 seconds with every line earning its place?", w: 6 },
  { k: "cta", label: "Is there ONE clear CTA at the end?", w: 6 },
  { k: "brand", label: "Does it match your visual brand (colors/fonts)?", w: 4 },
];

function ViralScore() {
  const [answers, setAnswers] = useState({});

  const score = SCORE_QUESTIONS.reduce((s, q) => s + (answers[q.k] ? q.w : 0), 0);

  const verdict = score >= 85 ? { label: "Viral probable", tone: "green", msg: "You've stacked enough winning elements. Post this — and double down on the pattern." }
                : score >= 65 ? { label: "Strong — tighten 1-2", tone: "accent", msg: "Good foundation. Tighten the weakest link below and post." }
                : score >= 40 ? { label: "Needs work", tone: "hot", msg: "Some pieces are there. But half your win-probability is missing — revisit hooks + value." }
                              : { label: "Don't post yet", tone: "hot", msg: "You're about to throw spaghetti. Research outlier hooks first, then rebuild." };

  return (
    <div className="widget">
      <div className="widget-head">
        <div>
          <div className="widget-label">VIRAL SCORE</div>
          <div className="widget-title">Score your next reel before you post it.</div>
        </div>
      </div>

      <div className="score-wrap">
        <div className="score-questions">
          {SCORE_QUESTIONS.map(q => (
            <label key={q.k} className={"score-row " + (answers[q.k] ? "is-on" : "")}>
              <input
                type="checkbox"
                checked={!!answers[q.k]}
                onChange={e => setAnswers(a => ({ ...a, [q.k]: e.target.checked }))}
              />
              <span className="score-check">
                <svg viewBox="0 0 14 14"><path d="M2 7L6 11L12 3" stroke="currentColor" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
              </span>
              <span className="score-label">{q.label}</span>
              <span className="score-weight mono">+{q.w}</span>
            </label>
          ))}
        </div>

        <div className="score-dial">
          <div className="dial">
            <svg viewBox="0 0 120 120">
              <circle cx="60" cy="60" r="52" fill="none" stroke="var(--line)" strokeWidth="8"/>
              <circle
                cx="60" cy="60" r="52"
                fill="none"
                stroke={verdict.tone === "green" ? "oklch(0.62 0.14 155)" : verdict.tone === "accent" ? "oklch(0.58 0.13 245)" : "oklch(0.65 0.18 28)"}
                strokeWidth="8"
                strokeLinecap="round"
                strokeDasharray={`${(score / 100) * 327} 327`}
                transform="rotate(-90 60 60)"
                style={{transition: "stroke-dasharray 500ms cubic-bezier(.2,.7,.2,1)"}}
              />
            </svg>
            <div className="dial-num">{score}</div>
            <div className="dial-label mono">/ 100</div>
          </div>
          <span className={"tag tag-" + verdict.tone}>{verdict.label}</span>
          <p className="score-msg">{verdict.msg}</p>
        </div>
      </div>
    </div>
  );
}

/* --------------------------------------------------------------------
   NICHE FINDER
-------------------------------------------------------------------- */
function NicheFinder() {
  const [main, setMain] = useState("");
  const [custom, setCustom] = useState("");
  const [picked, setPicked] = useState([]);

  const shownMain = main || "";
  const subs = SUB_NICHE_MAP[shownMain] || [];

  const toggle = (s) => {
    setPicked(p => p.includes(s) ? p.filter(x => x !== s) : p.length >= 7 ? p : [...p, s]);
  };

  const addCustom = () => {
    if (!custom.trim()) return;
    if (picked.length >= 7) return;
    setPicked(p => [...p, custom.trim()]);
    setCustom("");
  };

  return (
    <div className="widget">
      <div className="widget-head">
        <div>
          <div className="widget-label">NICHE FINDER</div>
          <div className="widget-title">Find your niche + 5-7 sub-niches.</div>
        </div>
        {picked.length > 0 && (
          <span className="mono" style={{color: "var(--muted)"}}>{picked.length}/7 picked</span>
        )}
      </div>

      <div>
        <label className="label">Step 1 · Pick your main niche</label>
        <div className="niche-chips">
          {MAIN_NICHES.map(n => (
            <button
              key={n}
              className={"chip " + (main === n ? "is-on" : "")}
              onClick={() => { setMain(n); setPicked([]); }}
            >{n}</button>
          ))}
        </div>
      </div>

      {main && (
        <div style={{marginTop: 28}}>
          <label className="label">Step 2 · Pick 5-7 sub-niches under {main}</label>
          <div className="niche-chips">
            {subs.map(s => (
              <button
                key={s}
                className={"chip chip-sub " + (picked.includes(s) ? "is-on" : "")}
                onClick={() => toggle(s)}
              >
                {picked.includes(s) && "✓ "}{s}
              </button>
            ))}
          </div>

          <div className="row" style={{marginTop: 14, gap: 8}}>
            <input
              type="text"
              placeholder="Add your own sub-niche…"
              value={custom}
              onChange={e => setCustom(e.target.value)}
              onKeyDown={e => e.key === "Enter" && addCustom()}
              style={{flex: 1}}
            />
            <button className="btn btn-ghost" onClick={addCustom}>Add</button>
          </div>
        </div>
      )}

      {picked.length >= 3 && (
        <div className="niche-result">
          <div className="mono label" style={{marginBottom: 10}}>YOUR CONTENT FOUNDATION</div>
          <div className="niche-summary">
            <strong>{main}</strong> creator focused on:
            <div className="niche-pills" style={{marginTop: 10}}>
              {picked.map(p => <span key={p} className="tag tag-accent">{p}</span>)}
            </div>
          </div>
          <p style={{marginTop: 14, fontSize: 14, color: "var(--muted)"}}>
            Rule: <strong style={{color: "var(--ink)"}}>one video = one sub-niche.</strong> Rotate through these 5-7 for the next 90 days.
          </p>
        </div>
      )}
    </div>
  );
}

/* --------------------------------------------------------------------
   QUIZ — What's your content style?
-------------------------------------------------------------------- */
function ContentStyleQuiz() {
  const [step, setStep] = useState(0);
  const [tally, setTally] = useState({ Teacher: 0, Storyteller: 0, Director: 0, Authority: 0 });

  const answer = (style) => {
    setTally(t => ({ ...t, [style]: t[style] + 1 }));
    setStep(s => s + 1);
  };

  const reset = () => { setStep(0); setTally({ Teacher: 0, Storyteller: 0, Director: 0, Authority: 0 }); };

  const done = step >= QUIZ.length;
  const winner = done ? Object.entries(tally).sort((a,b) => b[1]-a[1])[0][0] : null;
  const res = done ? QUIZ_RESULTS[winner] : null;

  if (done && res) {
    return (
      <div className="widget quiz-result">
        <div className="widget-label">YOUR CONTENT STYLE</div>
        <div className="quiz-title">You're <em>{res.title}</em>.</div>
        <p className="lead" style={{marginBottom: 28}}>{res.blurb}</p>

        <div className="quiz-grid">
          <div>
            <h4 className="subsub">Your best formats</h4>
            <ul className="list-dot">
              {res.bestFormats.map(f => <li key={f}>{f}</li>)}
            </ul>
          </div>
          <div>
            <h4 className="subsub">Hook styles that fit you</h4>
            <ul className="list-dot">
              {res.hookStyles.map(h => <li key={h}>{h}</li>)}
            </ul>
          </div>
        </div>

        <div className="callout" style={{marginTop: 28}}>
          Next step → {res.nextStep}
        </div>

        <button className="btn btn-ghost" onClick={reset}>↺ Retake the quiz</button>
      </div>
    );
  }

  const q = QUIZ[step];

  return (
    <div className="widget">
      <div className="widget-head">
        <div>
          <div className="widget-label">QUIZ · {step + 1} of {QUIZ.length}</div>
          <div className="widget-title">What's your content style?</div>
        </div>
        <div className="quiz-dots">
          {QUIZ.map((_, i) => (
            <span key={i} className={"quiz-dot " + (i < step ? "is-done" : i === step ? "is-now" : "")} />
          ))}
        </div>
      </div>

      <div className="quiz-q">{q.q}</div>
      <div className="quiz-options">
        {q.a.map((opt, i) => (
          <button key={i} className="quiz-opt" onClick={() => answer(opt.style)}>
            <span className="quiz-opt-letter mono">{String.fromCharCode(65 + i)}</span>
            <span className="quiz-opt-text">{opt.text}</span>
            <span className="quiz-opt-arrow">→</span>
          </button>
        ))}
      </div>
    </div>
  );
}

/* --------------------------------------------------------------------
   CHECKLIST
-------------------------------------------------------------------- */
function Checklist({ items, storageKey }) {
  const [checked, setChecked] = useState(() => {
    try { return JSON.parse(localStorage.getItem(storageKey) || "{}"); } catch { return {}; }
  });

  useEffect(() => {
    try { localStorage.setItem(storageKey, JSON.stringify(checked)); } catch {}
  }, [checked, storageKey]);

  const toggle = (i) => setChecked(c => ({ ...c, [i]: !c[i] }));
  const doneCount = items.filter((_, i) => checked[i]).length;

  return (
    <div className="widget">
      <div className="widget-head">
        <div>
          <div className="widget-label">YOUR GROWTH CHECKLIST</div>
          <div className="widget-title">Tick them off as you go.</div>
        </div>
        <div className="mono" style={{color: "var(--muted)"}}>
          {doneCount} / {items.length}
        </div>
      </div>

      <div className="checklist">
        {items.map((it, i) => (
          <div
            key={i}
            className={"check-item " + (checked[i] ? "is-checked" : "")}
            onClick={() => toggle(i)}
          >
            <span className="check-box">
              <svg viewBox="0 0 14 14">
                <path d="M2 7L6 11L12 3" stroke="currentColor" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            </span>
            <span className="check-text">
              {it.t}
              <small>{it.s}</small>
            </span>
          </div>
        ))}
      </div>
    </div>
  );
}

/* --------------------------------------------------------------------
   PHONE / REEL MOCKUP
-------------------------------------------------------------------- */
function ReelMockup({ hookText, caption, handle = "@marketing.shekhar", gradient }) {
  const grad = gradient || "linear-gradient(135deg, oklch(0.45 0.15 260 / 0.65), oklch(0.30 0.12 300 / 0.75), oklch(0.55 0.18 25 / 0.6))";
  return (
    <div className="phone">
      <div className="phone-screen">
        <div className="phone-gradient" style={{background: grad}} />
        <div className="phone-notch" />
        <div className="phone-ui">
          <div className="phone-hook-text" dangerouslySetInnerHTML={{__html: hookText}} />
          <div className="phone-bottom">
            <div className="phone-handle">{handle}</div>
            <div className="phone-caption">{caption}</div>
          </div>
        </div>
      </div>
    </div>
  );
}

/* Expose */
Object.assign(window, {
  HookGenerator, ScriptBuilder, ViralScore, NicheFinder,
  ContentStyleQuiz, Checklist, ReelMockup,
});
