// Personal Wellbeing Action Plan — intuitive, private, downloadable
function PlanPhase({ state, update, go }) {
  const p = state.plan;
  const [editing, setEditing] = useState(null);

  const setField = (key, value) => update("plan", { [key]: value });

  const fields = [
    { key: "trigger",    label: "My biggest current trigger",  hint: "what tends to set me off" },
    { key: "signal",     label: "My earliest warning signal",   hint: "what my body or mood does first" },
    { key: "reset",      label: "My reset tool",                hint: "the technique I'll use in the moment", fixedValue: "60-second breathing — 4 in, 6 out, ×3" },
    { key: "simplify",   label: "One thing to simplify or release", hint: "what I'll stop overcomplicating" },
    { key: "boundary",   label: "One boundary to strengthen",   hint: "the sentence I'll actually use" },
    { key: "recovery",   label: "One recovery habit",           hint: "sleep, movement, quiet, something restorative" },
    { key: "support",    label: "One support person",           hint: "who I can reach out to" },
    { key: "commitment", label: "My 7-day commitment",          hint: "one specific thing I will do this week" },
  ];

  const downloadPlan = () => {
    const safe = (v) => (v && v.trim()) ? v.trim() : "____________________";
    const today = new Date().toLocaleDateString("en-GB", { day: "numeric", month: "long", year: "numeric" });
    const html = `<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>My Personal Wellbeing Plan</title>
<style>
  @page { size: A4; margin: 20mm; }
  body { font-family: Georgia, "Times New Roman", serif; color: #1C1816; max-width: 720px; margin: 0 auto; padding: 24px; line-height: 1.5; }
  .top { border-bottom: 2px solid #C45A2C; padding-bottom: 14px; margin-bottom: 24px; }
  .eyebrow { font-family: -apple-system, "Segoe UI", sans-serif; font-size: 11px; letter-spacing: 0.18em; color: #C45A2C; text-transform: uppercase; margin-bottom: 6px; }
  h1 { font-size: 26px; font-weight: 500; margin: 0 0 6px; letter-spacing: -0.01em; }
  .date { font-family: -apple-system, "Segoe UI", sans-serif; font-size: 12px; color: #6B635C; }
  .intro { background: #FBF6EC; border-left: 3px solid #C45A2C; padding: 12px 16px; margin: 20px 0 28px; font-style: italic; font-size: 14px; color: #5A4A2E; }
  .row { padding: 14px 0; border-bottom: 1px solid #E8E2D9; }
  .row:last-child { border-bottom: none; }
  .label { font-family: -apple-system, "Segoe UI", sans-serif; font-size: 11px; letter-spacing: 0.1em; color: #6B635C; text-transform: uppercase; margin-bottom: 4px; }
  .value { font-size: 17px; color: #1C1816; min-height: 22px; }
  .pq { margin-top: 30px; padding: 16px; background: #1C1816; color: #F7F3EC; border-radius: 8px; font-style: italic; font-size: 16px; text-align: center; }
  .anchor { text-align: center; margin: 24px 0; }
  .anchor-word { font-size: 32px; color: #C45A2C; font-style: italic; }
  .footer { margin-top: 32px; font-family: -apple-system, "Segoe UI", sans-serif; font-size: 11px; color: #8A8079; text-align: center; border-top: 1px solid #E8E2D9; padding-top: 14px; }
  @media print { body { padding: 0; } }
</style></head><body>
  <div class="top">
    <div class="eyebrow">My Wellbeing Plan</div>
    <h1>Same pressure. Different carrying pattern.</h1>
    <div class="date">${today}</div>
  </div>
  <div class="intro">
    Everyone carries pressure differently. This plan is what <em>I</em> intuitively chose during today's session — a starting shape, not a final answer. I'll keep using it for the next seven days and adjust as I learn what works for me.
  </div>
  ${fields.map(f => `
    <div class="row">
      <div class="label">${f.label}</div>
      <div class="value">${f.fixedValue || safe(p[f.key])}</div>
    </div>`).join("")}
  ${state.guided.anchorWord ? `
    <div class="anchor">
      <div class="eyebrow">My anchor word</div>
      <div class="anchor-word">"${state.guided.anchorWord}"</div>
    </div>` : ""}
  <div class="pq">Insight becomes change when written into a plan.</div>
  <div class="footer">The Stress Reset</div>
</body></html>`;

    const w = window.open("", "_blank");
    if (!w) {
      // fallback: download as html file
      const blob = new Blob([html], { type: "text/html" });
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = "My-Wellbeing-Plan.html";
      a.click();
      return;
    }
    w.document.write(html);
    w.document.close();
    setTimeout(() => { try { w.print(); } catch (e) {} }, 400);
  };

  const renderField = (f) => {
    const value = f.fixedValue || p[f.key];
    const isFixed = !!f.fixedValue;
    const isEditing = editing === f.key;
    return (
      <div className="plan-row" key={f.key} onClick={() => !isFixed && !isEditing && setEditing(f.key)}>
        <div className="plan-label">{f.label}</div>
        {isEditing ? (
          <input
            className="input"
            value={p[f.key] || ""}
            placeholder={f.hint}
            onChange={(e) => setField(f.key, e.target.value)}
            onBlur={() => setEditing(null)}
            onKeyDown={(e) => e.key === "Enter" && setEditing(null)}
            autoFocus
          />
        ) : (
          <div className={`plan-value ${!value ? "empty" : ""} ${isFixed ? "fixed" : ""}`}>
            {value || `${f.hint} — tap to add`}
            {isFixed && <span style={{ fontSize: 11, color: "var(--ink-3)", marginLeft: 8 }}>· set</span>}
          </div>
        )}
      </div>
    );
  };

  const filledCount = fields.filter(f => f.fixedValue || (p[f.key] && p[f.key].trim())).length;

  return (
    <div className="phase">
      <Eyebrow>Your Wellbeing Plan</Eyebrow>
      <h1 className="display">This is the plan you built.</h1>

      <div className="plan-intro">
        <h3>Everyone is different. Including you.</h3>
        <p>
          There is no template that fits every person. Your stress, your warning signs, your boundaries, your support — they belong to you.
        </p>
        <p>
          Over the last 70 minutes, you've been intuitively assembling your own plan: noticing what you carry, what calms your body, what you can simplify, what you need to protect. The page below is just gathering it up. Tap any line to refine it.
        </p>
      </div>

      <window.PrivacyRibbon compact />

      <div className="card" style={{ padding: "4px 18px" }}>
        {fields.map(renderField)}
      </div>

      <div className="caption" style={{ marginTop: 10, textAlign: "center" }}>
        {filledCount} of {fields.length} filled in
      </div>

      <div className="download-row">
        <button className="dl-btn primary" onClick={downloadPlan}>
          <span className="dl-icon">
            <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
              <polyline points="7 10 12 15 17 10"/>
              <line x1="12" y1="15" x2="12" y2="3"/>
            </svg>
          </span>
          <span className="dl-text">
            <div className="dl-title">Download my plan</div>
            <div className="dl-sub">Save as PDF or print — it's yours</div>
          </span>
          <span className="dl-arrow">→</span>
        </button>
      </div>

      <div className="pullquote">
        Insight becomes change when written into a plan.
      </div>

      <div className="actions">
        <PrimaryButton onClick={() => go("close")}>Continue</PrimaryButton>
      </div>
    </div>
  );
}

window.PlanPhase = PlanPhase;
