/* Slow Weekend — "Your pace": an editable family profile.
   Reachable from the nav. Reads/writes the same sw_prefs the onboarding sets,
   so the two stay in lockstep. Calm, sectioned, live-editing that auto-saves on
   every change with a quiet "Saved" confirmation (no manual save bar). */

function Field({ label, hint, children }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      <div>
        <h3 style={{ font: "500 19px 'Source Serif 4', serif", color: "#2F2F2F", margin: 0, letterSpacing: "-0.01em" }}>{label}</h3>
        {hint && <p style={{ margin: "5px 0 0", fontSize: 13.5, color: "rgba(47,47,47,0.48)", lineHeight: 1.5 }}>{hint}</p>}
      </div>
      {children}
    </div>
  );
}

function Chip({ label, sub, on, onClick }) {
  return (
    <button onClick={onClick} style={{
      border: on ? "1px solid #7E9078" : "1px solid rgba(47,47,47,0.16)",
      cursor: "pointer", borderRadius: sub ? 13 : 999, font: "inherit",
      padding: sub ? "11px 16px" : "9px 17px", fontSize: 14, whiteSpace: "nowrap",
      background: on ? "rgba(126,144,120,0.14)" : "rgba(255,255,255,0.6)",
      color: on ? "#5d6b58" : "rgba(47,47,47,0.62)", transition: "all 0.3s ease", textAlign: "left",
    }}>
      <span style={{ fontWeight: on ? 600 : 500 }}>{label}</span>
      {sub && <span style={{ display: "block", marginTop: 2, fontSize: 12, fontWeight: 400, color: on ? "rgba(93,107,88,0.75)" : "rgba(47,47,47,0.4)" }}>{sub}</span>}
    </button>
  );
}

function ChipRow({ children }) {
  return <div style={{ display: "flex", flexWrap: "wrap", gap: 9 }}>{children}</div>;
}

function FamilyProfile({ prefs, onSave, onReplay }) {
  const makeDraft = () => ({
    ages: [], regions: [], intent: null, sensory: null,
    budget: null, energy: null,
    ...prefs,
  });
  const [draft, setDraft] = React.useState(makeDraft);
  const [savedAt, setSavedAt] = React.useState(false);

  // Auto-save: every change persists immediately (no manual save bar). The draft
  // and the stored prefs update together, and a quiet "Saved" pill confirms it.
  const commit = (next) => { setDraft(next); onSave(next); setSavedAt(true); };
  const set = (k, v) => commit({ ...draft, [k]: v });
  const toggle = (k, v) => {
    const arr = draft[k] || [];
    commit({ ...draft, [k]: arr.includes(v) ? arr.filter((x) => x !== v) : [...arr, v] });
  };
  const single = (k, v) => set(k, draft[k] === v ? null : v);

  // Let the "Saved" confirmation breathe, then slide it away on its own.
  React.useEffect(() => {
    if (!savedAt) return;
    const id = setTimeout(() => setSavedAt(false), 2600);
    return () => clearTimeout(id);
  }, [savedAt]);

  const summary = SW.prefSummary(draft);

  return (
    <div className="sw-fade" style={{ maxWidth: 760, margin: "0 auto", padding: "30px clamp(20px,6vw,64px) 140px" }}>
      {/* Header */}
      <div style={{ display: "flex", alignItems: "center", gap: 18, marginBottom: 10 }}>
        <span className="sw-breath" style={{ width: 46, height: 46, borderRadius: "50%", background: "radial-gradient(circle at 35% 30%, #C2A878, #7E9078)", flexShrink: 0 }} />
        <div>
          <span style={{ fontSize: 12.5, letterSpacing: "0.2em", textTransform: "uppercase", color: "rgba(47,47,47,0.4)" }}>Your pace</span>
          <h1 style={{ font: "500 clamp(28px,4vw,38px)/1.1 'Source Serif 4', serif", letterSpacing: "-0.02em", color: "#2F2F2F", margin: "6px 0 0" }}>The family profile</h1>
        </div>
      </div>
      <p style={{ fontSize: 16, lineHeight: 1.6, color: "rgba(47,47,47,0.58)", margin: "0 0 6px", maxWidth: 540 }}>
        Tune how we choose. Everything here quietly shapes your three weekly picks,{" "}
        {summary.length
          ? <>right now they lean <strong style={{ color: "#2F2F2F", fontWeight: 600 }}>{summary.join(" · ")}</strong>.</>
          : <>nothing set yet.</>}
      </p>

      <div style={{ display: "flex", flexDirection: "column", gap: 40, marginTop: 44 }}>
        <Field label="Who's in your family" hint="Helps us match the path to little legs.">
          <ChipRow>
            {SW.AGE_OPTS.map((a) => <Chip key={a} label={a} on={(draft.ages || []).includes(a)} onClick={() => toggle("ages", a)} />)}
          </ChipRow>
        </Field>

        <Field label="Where you wander" hint="The parts of the Bay Area you'll head to. Leave blank for everywhere.">
          <ChipRow>
            {SW.REGIONS.map((r) => <Chip key={r.key} label={r.label} on={(draft.regions || []).includes(r.key)} onClick={() => toggle("regions", r.key)} />)}
          </ChipRow>
        </Field>

        <Field label="This season's lean" hint="What your weekends mostly need to be right now.">
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(180px, 1fr))", gap: 12 }}>
            {SW.INTENTS.map((it) => {
              const on = draft.intent === it.key;
              return (
                <button key={it.key} onClick={() => single("intent", 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.6)",
                  cursor: "pointer", borderRadius: 15, padding: "18px 20px", font: "inherit", textAlign: "left", transition: "all 0.3s ease",
                }}>
                  <span style={{ display: "inline-flex", alignItems: "center", gap: 9, marginBottom: 7 }}>
                    <span style={{ width: 9, height: 9, borderRadius: "50%", background: it.accent }} />
                    <span style={{ font: "500 18px 'Source Serif 4', serif", color: "#2F2F2F" }}>{it.key}</span>
                  </span>
                  <span style={{ display: "block", fontSize: 13, color: "rgba(47,47,47,0.55)", lineHeight: 1.45 }}>{it.line}</span>
                </button>
              );
            })}
          </div>
        </Field>

        <Field label="Sensory load" hint="How much noise, crowd, and buzz feels right.">
          <ChipRow>
            {SW.SENSORY.map((s) => <Chip key={s.key} sub={s.note} label={s.label} on={draft.sensory === s.key} onClick={() => single("sensory", s.key)} />)}
          </ChipRow>
        </Field>

        <Field label="Budget" hint="How much an outing's price should shape your three.">
          <ChipRow>
            {SW.BUDGET.map((b) => <Chip key={b.key} label={b.label} on={draft.budget === b.key} onClick={() => single("budget", b.key)} />)}
          </ChipRow>
        </Field>

        <Field label="Your energy, most weekends" hint="How much you're usually up for. (Different from a single outing's intensity.)">
          <ChipRow>
            {SW.ENERGY.map((e) => <Chip key={e.key} sub={e.note} label={e.label} on={draft.energy === e.key} onClick={() => single("energy", e.key)} />)}
          </ChipRow>
        </Field>

        <div style={{ borderTop: "1px solid rgba(47,47,47,0.08)", paddingTop: 26, display: "flex", justifyContent: "space-between", alignItems: "center", gap: 16, flexWrap: "wrap" }}>
          <span style={{ fontSize: 14, color: "rgba(47,47,47,0.5)" }}>Prefer to start over?</span>
          <button onClick={onReplay} style={swGhostLink}>Replay onboarding →</button>
        </div>
      </div>

      {/* Quiet auto-save confirmation — every change saves on its own, so this is
          just a calm acknowledgment, not an action. Positioned via .sw-savebar CSS
          so it clears the fixed bottom tab bar on phones. */}
      <div className={"sw-savebar" + (savedAt ? " is-shown" : "")} style={{
        display: "flex", alignItems: "center", gap: 10,
        background: "#2F2F2F", color: "#F7F5F2", borderRadius: 999, padding: "12px 22px",
        boxShadow: "0 20px 50px -22px rgba(47,47,47,0.7)", maxWidth: "calc(100vw - 32px)",
      }}>
        <span style={{ fontSize: 14.5, whiteSpace: "nowrap" }}>Saved, your picks just updated</span>
      </div>
    </div>
  );
}

Object.assign(window, { FamilyProfile });
