/* mid.jsx — interactive Try-It plan generator + feature showcase */

const TRY_EXAMPLES = [
  {
    label: "Switch into product management in 6 months",
    score: 94, context: 82, strategy: 91,
    partA: [
      "Position your existing strengths as PM-adjacent, not a restart",
      "Target 2 industries where your domain knowledge compounds",
      "Build proof: one shipped case study beats ten cover letters",
    ],
    partB: [
      "Map the exact PM skills gap for your target roles",
      "Draft a 3-sentence cold outreach to 5 PMs this week",
      "Ship a teardown of a product you use daily",
    ],
  },
  {
    label: "Launch my side project while working full-time",
    score: 92, context: 79, strategy: 90,
    partA: [
      "Validate the idea fast and imperfectly before building",
      "Protect 5 focused hours/week — sustainable beats sprints",
      "Build an audience while you build the product",
    ],
    partB: [
      "Write the one-sentence problem you're solving",
      "Set up a simple landing page placeholder this weekend",
      "List the top 3 competitor platforms and their gaps",
    ],
  },
  {
    label: "Build a sustainable daily writing habit",
    score: 95, context: 85, strategy: 92,
    partA: [
      "Anchor writing to an existing daily cue (Atomic Habits)",
      "Lower the bar: 2 sentences counts as a win",
      "Track the chain, not the word count",
    ],
    partB: [
      "Pick a fixed 15-minute slot and put it on the calendar",
      "Write your first 2 sentences right after coffee tomorrow",
      "Set a gentle coach check-in for day 3",
    ],
  },
];

function genericPlan(goal) {
  const g = goal.trim().replace(/\.$/, "");
  return {
    score: 90, context: 78, strategy: 88,
    partA: [
      "Clarify what \u201Cdone\u201D looks like and why it matters now",
      "Focus on the one lever that moves \u201C" + (g.length > 38 ? g.slice(0, 38) + "\u2026" : g) + "\u201D most",
      "Design for sustainability, not a burnout sprint",
    ],
    partB: [
      "Write the single most important first step you can do today",
      "Block 3 focused sessions on the calendar this week",
      "Set a coach check-in to keep momentum on day 3",
    ],
  };
}

function TryIt() {
  const [value, setValue] = React.useState("");
  const [state, setState] = React.useState("idle"); // idle | loading | done
  const [result, setResult] = React.useState(null);
  const [score, setScore] = React.useState(0);

  const run = (goalText) => {
    const text = (goalText ?? value).trim();
    if (!text) return;
    setValue(text);
    setState("loading"); setScore(0); setResult(null);
    const match = TRY_EXAMPLES.find((e) => e.label.toLowerCase() === text.toLowerCase());
    const plan = match || genericPlan(text);
    setTimeout(() => {
      setResult(plan); setState("done");
      // count up score
      const target = plan.score; const start = performance.now(); const dur = 900;
      const tick = (now) => {
        const p = Math.min((now - start) / dur, 1);
        const eased = 1 - Math.pow(1 - p, 3);
        setScore(Math.round(eased * target));
        if (p < 1) requestAnimationFrame(tick);
      };
      requestAnimationFrame(tick);
    }, 1150);
  };

  const C = 2 * Math.PI * 34;
  const pct = result ? score / 100 : 0;

  return (
    <section className="tryit" id="try">
      <div className="wrap">
        <div className="sec-head center">
          <p className="eyebrow" data-reveal>Try it — right here</p>
          <h2 data-reveal data-delay="1">Type a goal. Watch it become a scored plan.</h2>
          <p className="lede" data-reveal data-delay="2">This is the moment everything turns on — a real plan and a quality score in seconds. No signup to look.</p>
        </div>

        <div className="try-card" data-reveal>
          <div className="try-inner">
            <div className="try-left">
              <div className="glabel">Your goal</div>
              <textarea
                className="try-input"
                placeholder="e.g. Move into a senior design role within a year"
                value={value}
                onChange={(e) => setValue(e.target.value)}
                onKeyDown={(e) => { if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) run(); }}
              />
              <div className="try-chips">
                {TRY_EXAMPLES.map((e) => (
                  <button key={e.label} className="try-chip" onClick={() => run(e.label)}>{e.label}</button>
                ))}
              </div>
              <button className="btn btn-primary" style={{ marginTop: 22 }} onClick={() => run()}>
                {state === "loading" ? "Thinking\u2026" : "Generate my plan"} <Icon.spark style={{ marginLeft: 2 }} />
              </button>
              <p className="try-note">A live preview — your real plan saves to your dashboard once you start.</p>
            </div>

            <div className="try-right">
              {state === "idle" && (
                <div className="placeholder">
                  <div className="pmark"><Icon.target style={{ color: "rgba(255,255,255,.5)" }} /></div>
                  <div style={{ fontWeight: 600, color: "rgba(255,255,255,.7)" }}>Your scored plan appears here</div>
                  <div style={{ fontSize: 13.5, marginTop: 6 }}>Pick an example or type your own goal</div>
                </div>
              )}
              {state === "loading" && (
                <div className="placeholder">
                  <div className="pmark"><span className="spin"><Icon.spark style={{ color: "var(--accent)" }} /></span></div>
                  <div style={{ fontWeight: 600, color: "rgba(255,255,255,.7)" }}>Drafting strategy &amp; scoring…</div>
                </div>
              )}
              {state === "done" && result && (
                <div className="try-result reveal-stagger" key={value}>
                  <div className="try-score" style={{ animationDelay: "0s" }}>
                    <div className="try-gauge">
                      <svg width="80" height="80">
                        <circle cx="40" cy="40" r="34" stroke="rgba(255,255,255,.12)" strokeWidth="7" fill="none" />
                        <circle cx="40" cy="40" r="34" stroke="var(--green)" strokeWidth="7" fill="none"
                          strokeLinecap="round" strokeDasharray={C} strokeDashoffset={C * (1 - pct)}
                          style={{ transition: "stroke-dashoffset .1s linear" }} />
                      </svg>
                      <div className="gval">{score}</div>
                    </div>
                    <div className="meta">
                      <div className="t">Strategy Score</div>
                      <div className="v">Strong plan — ready to execute</div>
                      <div style={{ display: "flex", gap: 14, marginTop: 10 }}>
                        <Metric label="Context" val={result.context} color="var(--blue)" />
                        <Metric label="Strategy" val={result.strategy} color="var(--accent)" />
                      </div>
                    </div>
                  </div>
                  <div className="try-divider" style={{ animationDelay: ".05s" }} />
                  <div className="try-block" style={{ animationDelay: ".1s" }}>
                    <div className="bt"><Icon.target style={{ color: "var(--accent)" }} /> Part A <span className="pill">Strategy</span></div>
                    {result.partA.map((t, i) => (
                      <div className="try-li" key={i}><span className="ic a"><Icon.spark /></span><span>{t}</span></div>
                    ))}
                  </div>
                  <div className="try-block" style={{ animationDelay: ".18s" }}>
                    <div className="bt" style={{ color: "var(--green)" }}><Icon.layers style={{ color: "var(--green)" }} /> Part B <span className="pill" style={{ background: "rgba(14,166,107,.18)" }}>Execution</span></div>
                    {result.partB.map((t, i) => (
                      <div className="try-li" key={i}><span className="ic"><Icon.checkCircle /></span><span>{t}</span></div>
                    ))}
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function Metric({ label, val, color }) {
  return (
    <div style={{ minWidth: 88 }}>
      <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11, color: "rgba(255,255,255,.5)", fontFamily: "var(--mono)", letterSpacing: ".06em" }}>
        <span>{label}</span><span>{val}</span>
      </div>
      <div style={{ height: 5, borderRadius: 99, background: "rgba(255,255,255,.1)", marginTop: 5, overflow: "hidden" }}>
        <i style={{ display: "block", height: "100%", width: val + "%", background: color, borderRadius: 99, transition: "width .9s var(--ease) .2s" }} />
      </div>
    </div>
  );
}

const FEATURES = [
  {
    eyebrow: "Scored plans", icon: "gauge",
    title: "A quality score on every plan",
    lede: "Gen Coach evaluates context clarity and strategy quality, then suggests refinements — so you don't just get a plan, you get a good one.",
    img: "assets/plan-details.png", alt: "Plan details with strategy and context scores",
    addr: "gencoach.app/plan",
    list: [
      ["Two-part structure", "Strategy and execution, separated and scored.", false],
      ["Coach perspectives", "Switch experts to re-score from a new angle.", false],
      ["Framework-aware", "Stoic, OKR, GTD, Atomic — baked into the plan.", true],
    ],
  },
  {
    eyebrow: "AI coaches with memory", icon: "brain",
    title: "A coach that actually remembers you",
    lede: "Choose a specialized coach for your goal. It carries your context from day one — every conversation is personalized, never a cold prompt.",
    img: "assets/marketplace.png", alt: "Marketplace of specialized AI coaches",
    addr: "gencoach.app/coaches",
    list: [
      ["16+ specialized coaches", "Career, strategy, analytics, behavior, and more.", false],
      ["Long-term memory", "Your goals and working style persist across sessions.", true],
      ["Swap anytime", "Different perspective in one tap, same context.", false],
    ],
  },
  {
    eyebrow: "Daily accompaniment", icon: "chat",
    title: "Check-ins that move you forward",
    lede: "Your coach converses daily, nudges gently when you stall, and helps you decide what matters today — warm and sharp, never preachy or pushy.",
    img: "assets/chat.png", alt: "Chat with an AI coach",
    addr: "gencoach.app/chat",
    list: [
      ["Smart suggestions", "“What should I focus on today?” answered in context.", false],
      ["Gentle accountability", "Nudges, not guilt-trips. Continue when you're ready.", true],
      ["Progress reviews", "Quick pulse on where your plans stand.", false],
    ],
  },
  {
    eyebrow: "Execution", icon: "cal",
    title: "Your plan becomes a week you can see",
    lede: "Drag tasks onto the calendar, batch them into sprints, and watch progress tick up. The plan stops being a wish and becomes a schedule.",
    img: "assets/calendar.png", alt: "Calendar with scheduled tasks",
    addr: "gencoach.app/calendar",
    list: [
      ["Drag-to-schedule", "Move tasks from plan to calendar in seconds.", false],
      ["Task types", "Goal, Quick Win, Process, Stop, Safeguard — color-coded.", false],
      ["30/90-day sprints", "Time-boxed focus on a single goal.", true],
    ],
  },
];

function Features() {
  return (
    <section className="sec" id="features" style={{ paddingBottom: 60 }}>
      <div className="wrap">
        <div className="sec-head center" style={{ marginBottom: 40 }}>
          <p className="eyebrow" data-reveal>Inside Gen Coach</p>
          <h2 data-reveal data-delay="1">Everything you need to follow through</h2>
        </div>
        {FEATURES.map((f, i) => (
          <Feature key={i} f={f} />
        ))}
      </div>
    </section>
  );
}

function Feature({ f }) {
  const I = Icon[f.icon];
  return (
    <div className="feat">
      <div className="feat-copy" data-reveal>
        <p className="eyebrow"><I style={{ color: "var(--accent)" }} /> {f.eyebrow}</p>
        <h2 style={{ fontSize: "clamp(26px,3vw,38px)" }}>{f.title}</h2>
        <p className="lede">{f.lede}</p>
        <div className="feat-list">
          {f.list.map(([b, s, g], j) => (
            <div className="fli" key={j}>
              <span className={"ic" + (g ? " g" : "")}><Icon.check /></span>
              <span><b>{b}</b> — {s}</span>
            </div>
          ))}
        </div>
      </div>
      <div className="feat-shot" data-reveal data-delay="1">
        <div className="shot-bar">
          <span className="dot" /><span className="dot" /><span className="dot" />
          <span className="addr">{f.addr}</span>
        </div>
        <img src={f.img} alt={f.alt} />
      </div>
    </div>
  );
}

Object.assign(window, { TryIt, Features });
