/* Slow Weekend — onboarding.
   A gentle, low-pressure first-run flow that sets the family's pace.
   Mirrors the calming intro: breathing orb, Source Serif questions, soft chips.
   Depth (minimal | standard | full) is set via Tweaks. On completion it writes
   `sw_prefs` (seeds Home + the family profile) and `sw_onboarded`. */

function readPrefs() { return SW.readPrefs(); }

/* Step recipes per depth. Welcome + ready bookend every flow. */
const SW_FLOWS = {
  minimal:  ["welcome", "cities", "intent", "ready"],
  standard: ["welcome", "ages", "cities", "intent", "energy", "budget", "ready"],
  full:     ["welcome", "ages", "cities", "intent", "sensory", "energy", "budget", "ready"],
};

/* A soft chip in the language of the home filters. */
function OnbChip({ label, on, onClick, sublabel, big }) {
  return (
    <button onClick={onClick} style={{
      border: on ? "1px solid #7E9078" : "1px solid rgba(47,47,47,0.16)",
      cursor: "pointer", borderRadius: big ? 16 : 999, font: "inherit",
      padding: big ? "18px 22px" : "11px 20px",
      fontSize: big ? 16 : 14.5, whiteSpace: "nowrap",
      background: on ? "rgba(126,144,120,0.14)" : "rgba(255,255,255,0.5)",
      color: on ? "#5d6b58" : "rgba(47,47,47,0.6)",
      transition: "all 0.35s ease", textAlign: "left",
      display: big ? "block" : "inline-block", width: big ? "100%" : "auto",
    }}>
      <span style={{ fontWeight: on ? 600 : 500 }}>{label}</span>
      {sublabel && <span style={{ display: "block", marginTop: 4, fontSize: 13, fontWeight: 400, color: on ? "rgba(93,107,88,0.8)" : "rgba(47,47,47,0.42)", whiteSpace: "normal" }}>{sublabel}</span>}
    </button>
  );
}

function Onboarding({ onDone, minimal, depth = "standard" }) {
  const existing = SW.readPrefs();
  const STEPS = SW_FLOWS[depth] || SW_FLOWS.standard;
  const total = STEPS.length;

  const [step, setStep] = React.useState(0);
  const [ages, setAges] = React.useState(existing.ages || []);
  const [picked, setPicked] = React.useState(existing.cities || ["SF Bay Area"]);
  const [intent, setIntent] = React.useState(existing.intent || null);
  const [sensory, setSensory] = React.useState(existing.sensory || null);
  const [energy, setEnergy] = React.useState(existing.energy || null);
  const [budget, setBudget] = React.useState(existing.budget || null);

  const kind = STEPS[step];
  const terse = minimal; // hide helper subtitles when "minimal" copy is on

  const toggle = (arr, set, v) => set(arr.includes(v) ? arr.filter((x) => x !== v) : [...arr, v]);
  const go = (d) => setStep((s) => Math.min(total - 1, Math.max(0, s + d)));

  const finish = (skip) => {
    const prefs = skip
      ? { ...existing, skipped: true }
      : { ...existing, ages, cities: picked.length ? picked : ["SF Bay Area"], intent, sensory, energy, budget };
    SW.writePrefs(prefs);
    onDone(prefs);
  };

  // Single-select steps advance on their own gentle beat.
  const choose = (set, v) => { set(v); setTimeout(() => go(1), 360); };

  const orb = (size) => (
    <span style={{ width: size, height: size, borderRadius: "50%", background: "radial-gradient(circle at 35% 30%, #C2A878, #7E9078)" }} />
  );

  let content;
  if (kind === "welcome") {
    content = (
      <div style={{ textAlign: "center", maxWidth: 520 }}>
        <div className="sw-breath" style={{ display: "inline-block", marginBottom: 34 }}>{orb(56)}</div>
        <h1 style={{ font: "500 clamp(30px,4.6vw,44px)/1.1 'Source Serif 4', serif", letterSpacing: "-0.02em", color: "#2F2F2F", margin: "0 0 18px" }}>
          Let's set your pace
        </h1>
        <p style={{ fontSize: 17.5, lineHeight: 1.55, color: "rgba(47,47,47,0.6)", margin: "0 auto", maxWidth: 420 }}>
          A few quiet questions, then we'll narrow every weekend down to three outings worth your energy. No accounts, no rush.
        </p>
        <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 14, marginTop: 38 }}>
          <button onClick={() => go(1)} style={swPrimaryBtn}>Begin</button>
          <button onClick={() => finish(true)} style={swGhostLink}>Skip for now</button>
        </div>
      </div>
    );
  } else if (kind === "ages") {
    content = (
      <StepBody title="Who's coming along?" sub={terse ? null : "So we match the pace and the path to little legs. Pick any that fit."}>
        <div style={swWrap(540)}>
          {SW.AGE_OPTS.map((a) => (
            <OnbChip key={a} label={a} on={ages.includes(a)} onClick={() => toggle(ages, setAges, a)} />
          ))}
        </div>
        <ContinueRow onBack={() => go(-1)} onNext={() => go(1)} />
      </StepBody>
    );
  } else if (kind === "cities") {
    content = (
      <StepBody title="Where do you wander?" sub={terse ? null : "We'll keep suggestions close to home. Choose your corners of the Peninsula."}>
        <div style={swWrap(560)}>
          {SW.CITY_OPTS.map((c) => (
            <OnbChip key={c} label={c} on={picked.includes(c)} onClick={() => toggle(picked, setPicked, c)} />
          ))}
        </div>
        <ContinueRow onBack={() => go(-1)} onNext={() => go(1)} disabled={!picked.length} />
      </StepBody>
    );
  } else if (kind === "intent") {
    content = (
      <StepBody title="What does this weekend need to be?" sub={terse ? null : "There's no wrong answer, just where your family is right now."}>
        <div style={{ display: "grid", gap: 14, width: "100%", maxWidth: 440 }}>
          {SW.INTENTS.map((it) => {
            const on = intent === it.key;
            return (
              <button key={it.key} onClick={() => choose(setIntent, it.key)} style={{
                border: on ? `1px solid ${it.accent}` : "1px solid rgba(47,47,47,0.14)",
                background: on ? `${it.accent}1f` : "rgba(255,255,255,0.55)",
                cursor: "pointer", borderRadius: 16, padding: "20px 24px", font: "inherit",
                textAlign: "left", display: "flex", alignItems: "center", gap: 16, transition: "all 0.35s ease",
              }}>
                <span style={{ width: 12, height: 12, borderRadius: "50%", background: it.accent, flexShrink: 0 }} />
                <span>
                  <span style={{ font: "500 20px 'Source Serif 4', serif", color: "#2F2F2F", display: "block" }}>{it.key}</span>
                  <span style={{ fontSize: 14, color: "rgba(47,47,47,0.55)" }}>{it.line}</span>
                </span>
              </button>
            );
          })}
        </div>
        <ContinueRow onBack={() => go(-1)} onNext={() => go(1)} disabled={!intent} />
      </StepBody>
    );
  } else if (kind === "sensory") {
    content = (
      <StepBody title="How much buzz can you take?" sub={terse ? null : "We'll lean your picks toward the right sensory load."}>
        <div style={{ display: "grid", gap: 12, width: "100%", maxWidth: 440 }}>
          {SW.SENSORY.map((s) => (
            <OnbChip key={s.key} big label={s.label} sublabel={s.note} on={sensory === s.key} onClick={() => choose(setSensory, s.key)} />
          ))}
        </div>
        <ContinueRow onBack={() => go(-1)} onNext={() => go(1)} disabled={!sensory} />
      </StepBody>
    );
  } else if (kind === "energy") {
    content = (
      <StepBody title="How much is in the tank?" sub={terse ? null : "Honest answers make for gentler weekends."}>
        <div style={{ display: "grid", gap: 12, width: "100%", maxWidth: 440 }}>
          {SW.ENERGY.map((e) => (
            <OnbChip key={e.key} big label={e.label} sublabel={e.note} on={energy === e.key} onClick={() => choose(setEnergy, e.key)} />
          ))}
        </div>
        <ContinueRow onBack={() => go(-1)} onNext={() => go(1)} disabled={!energy} />
      </StepBody>
    );
  } else if (kind === "budget") {
    content = (
      <StepBody title="Does price matter this season?" sub={terse ? null : "We'll weight your three toward free or paid to match."}>
        <div style={{ display: "grid", gap: 12, width: "100%", maxWidth: 440 }}>
          {SW.BUDGET.map((b) => (
            <OnbChip key={b.key} big label={b.label} sublabel={b.note} on={budget === b.key} onClick={() => choose(setBudget, b.key)} />
          ))}
        </div>
        <ContinueRow onBack={() => go(-1)} onNext={() => go(1)} disabled={!budget} />
      </StepBody>
    );
  } else {
    content = (
      <div style={{ textAlign: "center", maxWidth: 500 }}>
        <div className="sw-breath" style={{ display: "inline-block", marginBottom: 32 }}>{orb(50)}</div>
        <h1 style={{ font: "500 clamp(28px,4.2vw,40px)/1.12 'Source Serif 4', serif", letterSpacing: "-0.02em", color: "#2F2F2F", margin: "0 0 16px" }}>
          That's all we need
        </h1>
        <p style={{ fontSize: 17, lineHeight: 1.55, color: "rgba(47,47,47,0.6)", margin: "0 auto 6px", maxWidth: 400 }}>
          We'll keep it to three picks{intent ? <>, leaning <strong style={{ color: "#2F2F2F", fontWeight: 600 }}>{intent.toLowerCase()}</strong></> : ""}{picked.length ? <> around <strong style={{ color: "#2F2F2F", fontWeight: 600 }}>{picked[0]}{picked.length > 1 ? ` +${picked.length - 1}` : ""}</strong></> : ""}.
        </p>
        <p style={{ font: "400 17px 'Source Serif 4', serif", color: "rgba(47,47,47,0.5)", fontStyle: "italic", margin: "20px 0 36px" }}>
          A good weekend is one you don't need to recover from.
        </p>
        <button onClick={() => finish(false)} style={swPrimaryBtn}>See my weekend</button>
      </div>
    );
  }

  return (
    <div style={{
      position: "fixed", inset: 0, zIndex: 95, background: "#F7F5F2",
      display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
      padding: "72px 24px 40px", overflowY: "auto",
    }}>
      <div style={{ position: "absolute", top: 30, left: "50%", transform: "translateX(-50%)", display: "flex", gap: 7 }}>
        {STEPS.map((_, i) => (
          <span key={i} style={{
            height: 5, borderRadius: 999, transition: "all 0.5s ease",
            width: i === step ? 26 : 5,
            background: i <= step ? "#7E9078" : "rgba(47,47,47,0.14)",
          }} />
        ))}
      </div>

      <div key={step} className="sw-stepin" style={{ display: "flex", flexDirection: "column", alignItems: "center", width: "100%" }}>
        {content}
      </div>
    </div>
  );
}

/* ---- shared bits (sw-prefixed to avoid global collisions) ---- */

const swPrimaryBtn = {
  border: "none", cursor: "pointer", borderRadius: 999, padding: "15px 34px", fontSize: 15.5,
  font: "inherit", fontWeight: 500, background: "#2F2F2F", color: "#F7F5F2",
  boxShadow: "0 16px 34px -18px rgba(47,47,47,0.6)", whiteSpace: "nowrap",
};
const swGhostLink = {
  border: "none", background: "none", cursor: "pointer", font: "inherit", fontSize: 14,
  color: "rgba(47,47,47,0.45)", padding: "6px 10px",
};
const swWrap = (max) => ({ display: "flex", flexWrap: "wrap", gap: 11, justifyContent: "center", maxWidth: max });

function StepBody({ title, sub, children }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", alignItems: "center", textAlign: "center", width: "100%" }}>
      <h1 style={{ font: "500 clamp(26px,3.8vw,38px)/1.14 'Source Serif 4', serif", letterSpacing: "-0.02em", color: "#2F2F2F", margin: "0 0 12px", maxWidth: 560 }}>{title}</h1>
      {sub ? <p style={{ fontSize: 16, lineHeight: 1.5, color: "rgba(47,47,47,0.55)", margin: "0 0 34px", maxWidth: 440 }}>{sub}</p> : <div style={{ height: 22 }} />}
      {children}
    </div>
  );
}

function ContinueRow({ onBack, onNext, disabled, nextLabel = "Continue" }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 18, marginTop: 40 }}>
      <button onClick={onBack} style={swGhostLink}>← Back</button>
      <button onClick={disabled ? undefined : onNext} disabled={disabled} style={{
        ...swPrimaryBtn, opacity: disabled ? 0.4 : 1, cursor: disabled ? "default" : "pointer",
        boxShadow: disabled ? "none" : swPrimaryBtn.boxShadow,
      }}>{nextLabel}</button>
    </div>
  );
}

Object.assign(window, { Onboarding, readPrefs, OnbChip, swPrimaryBtn, swGhostLink });
