/* global React, Icon, Button, cx, CATEGORIES, CAT, US_STATES, LEARNER */
// LPE Learning Center — Settings screen + first-run Onboarding.

const { useState: useStateSet, useEffect: useEffectSet } = React;

function Switch({ on, onChange }) {
  return <button type="button" className={cx("switch", on && "on")} onClick={() => onChange(!on)} aria-pressed={on}><span className="knob" /></button>;
}

function ToggleRow({ title, desc, on, onChange }) {
  return (
    <div className="toggle-row">
      <div className="tr-info"><div className="t">{title}</div><div className="d">{desc}</div></div>
      <Switch on={on} onChange={onChange} />
    </div>
  );
}

function SettingsScreen({ learner, updateLearner, tweaks, setTweak, onToast, onSignOut, onDeleteAccount }) {
  const [section, setSection] = useStateSet("profile");
  const [localLearner, setLocalLearner] = useStateSet(learner);

  useEffectSet(() => {
    setLocalLearner(learner);
  }, [learner]);

  const prefs = localLearner.notificationPrefs || {};
  const setPref = (k, v) => {
    const nextPrefs = { ...prefs, [k]: v };
    setLocalLearner(prev => ({ ...prev, notificationPrefs: nextPrefs }));
    updateLearner({ notificationPrefs: nextPrefs });
  };

  function handleSave(message) {
    updateLearner(localLearner);
    onToast(message);
  }

  const NAV = [["profile", "Profile"], ["bar", "Bar & CLE"], ["notifications", "Notifications"], ["display", "Display"], ["account", "Account"]];

  return (
    <div className="lc-page">
      <div className="page-header">
        <div className="ph-title">
          <div className="eyebrow">Settings</div>
          <h1>Account settings</h1>
          <p className="subtitle">Manage your profile, bar information for CLE tracking, and how the Learning Center notifies you.</p>
        </div>
      </div>

      <div className="set-shell">
        <nav className="set-nav">
          {NAV.map(([id, lab]) => (
            <button key={id} className={cx(section === id && "active")} onClick={() => setSection(id)}>{lab}</button>
          ))}
        </nav>

        <div>
          {section === "profile" ? (
            <div className="set-section">
              <h3>Profile</h3>
              <p className="sh-sub">This is how you appear across the Learning Center.</p>
              <div className="form-2col">
                <div className="form-field"><label>Full name</label><input value={localLearner.name || ""} onChange={(e) => setLocalLearner({ ...localLearner, name: e.target.value })} /></div>
                <div className="form-field"><label>Firm</label><input value={localLearner.firm || ""} onChange={(e) => setLocalLearner({ ...localLearner, firm: e.target.value })} /></div>
              </div>
              <div className="form-2col">
                <div className="form-field"><label>Role</label>
                  <select value={localLearner.role || "Buyer member"} onChange={(e) => setLocalLearner({ ...localLearner, role: e.target.value })}>
                    {["Buyer member", "Seller member", "Advisor", "Sponsor"].map((r) => <option key={r}>{r}</option>)}
                  </select>
                </div>
                <div className="form-field"><label>Email</label><input type="email" value={localLearner.email || ""} onChange={(e) => setLocalLearner({ ...localLearner, email: e.target.value })} /></div>
              </div>
              <Button variant="primary" icon="check" onClick={() => handleSave("Profile saved")}>Save changes</Button>
            </div>
          ) : null}

          {section === "bar" ? (
            <div className="set-section">
              <h3>Bar &amp; CLE tracking</h3>
              <p className="sh-sub">We use this to track your reporting cycle and generate certificates and affidavits.</p>
              <div className="form-2col">
                <div className="form-field"><label>Primary bar jurisdiction</label>
                  <select value={localLearner.targetState || "Ohio"} onChange={(e) => setLocalLearner({ ...localLearner, targetState: e.target.value, barState: e.target.value })}>
                    {US_STATES.map((s) => <option key={s}>{s}</option>)}
                  </select>
                </div>
                <div className="form-field"><label>Bar number</label><input value={localLearner.barNo || ""} onChange={(e) => setLocalLearner({ ...localLearner, barNo: e.target.value })} /></div>
              </div>
              <div className="form-2col">
                <div className="form-field">
                  <label>Reporting period start</label>
                  <input value={localLearner.reportingPeriod ? localLearner.reportingPeriod.start : ""} onChange={(e) => setLocalLearner({ ...localLearner, reportingPeriod: { ...(localLearner.reportingPeriod || { start: "", end: "" }), start: e.target.value } })} placeholder="e.g. Jan 1, 2026" />
                </div>
                <div className="form-field">
                  <label>Reporting period end</label>
                  <input value={localLearner.reportingPeriod ? localLearner.reportingPeriod.end : ""} onChange={(e) => setLocalLearner({ ...localLearner, reportingPeriod: { ...(localLearner.reportingPeriod || { start: "", end: "" }), end: e.target.value } })} placeholder="e.g. Dec 31, 2027" />
                </div>
              </div>
              <div style={{ height: 12 }} />
              <Button variant="primary" icon="check" onClick={() => handleSave("Bar information saved")}>Save changes</Button>
            </div>
          ) : null}

          {section === "notifications" ? (
            <div className="set-section">
              <h3>Notifications</h3>
              <p className="sh-sub">Choose what we email you about. In-app notifications always appear in the bell menu.</p>
              <ToggleRow title="Live session reminders" desc="A reminder before sessions you've registered for." on={prefs.liveReminders} onChange={(v) => setPref("liveReminders", v)} />
              <ToggleRow title="New sessions in your interests" desc="When we publish a session in a topic you follow." on={prefs.newInInterests} onChange={(v) => setPref("newInInterests", v)} />
              <ToggleRow title="Certificate ready" desc="When a CLE certificate is available to download." on={prefs.certificateReady} onChange={(v) => setPref("certificateReady", v)} />
              <ToggleRow title="Weekly digest" desc="A Monday summary of new sessions and your progress." on={prefs.weeklyDigest} onChange={(v) => setPref("weeklyDigest", v)} />
            </div>
          ) : null}

          {section === "display" ? (
            <div className="set-section">
              <h3>Display</h3>
              <p className="sh-sub">Personalize how the Learning Center looks. These mirror the live tweak controls.</p>
              <div className="form-field"><label>Theme accent</label>
                <div style={{ display: "flex", gap: 10 }}>
                  {[["#E47425", "Signature orange"], ["#1B7F7C", "Teal"], ["#C9A876", "Gold"]].map(([hex, lab]) => (
                    <button key={hex} type="button" onClick={() => setTweak("accent", hex)}
                      className={cx("ob-opt", tweaks.accent === hex && "sel")} style={{ flex: 1, justifyContent: "flex-start" }}>
                      <span style={{ width: 18, height: 18, background: hex, flexShrink: 0 }} />{lab}
                    </button>
                  ))}
                </div>
              </div>
              <div className="form-field"><label>Default library view</label>
                <div style={{ display: "flex", gap: 10 }}>
                  {[["grid", "Grid"], ["list", "List"]].map(([id, lab]) => (
                    <button key={id} type="button" onClick={() => setTweak("libraryView", id)} className={cx("ob-opt", tweaks.libraryView === id && "sel")} style={{ flex: 1 }}>
                      <Icon name={id === "grid" ? "grid" : "list"} size={16} />{lab}
                    </button>
                  ))}
                </div>
              </div>
            </div>
          ) : null}

          {section === "account" ? (
            <div className="set-section">
              <h3>Account</h3>
              <p className="sh-sub">Member since {learner.memberSince}.</p>
              <div style={{ display: "flex", flexDirection: "column", gap: 12, maxWidth: 320 }}>
                <Button variant="secondary" icon="logout" onClick={onSignOut}>Sign out</Button>
                <Button variant="ghost" icon="x" onClick={() => {
                  if (confirm("Are you sure you want to permanently delete your account? This action cannot be undone.")) {
                    onDeleteAccount();
                  }
                }} style={{ color: "var(--orange-700)" }}>Delete account</Button>
              </div>
            </div>
          ) : null}
        </div>
      </div>
    </div>
  );
}

// ---------- Onboarding (first-run) ----------
const ROLES = [
  { id: "Buyer member", icon: "market", desc: "Acquiring or building a practice" },
  { id: "Seller member", icon: "tag", desc: "Planning a sale or succession" },
  { id: "Advisor", icon: "handshake", desc: "Broker or deal intermediary" },
  { id: "Sponsor", icon: "dollar", desc: "Private equity / roll-up platform" },
];

function Onboarding({ learner, onComplete }) {
  const [step, setStep] = useStateSet(1);
  const [role, setRole] = useStateSet(learner.role || "Buyer member");
  const [interests, setInterests] = useStateSet(learner.interests || []);
  const [state, setState] = useStateSet(learner.targetState || "Ohio");
  const [barNo, setBarNo] = useStateSet(learner.barNo || "");

  const toggleInterest = (id) => setInterests((xs) => xs.includes(id) ? xs.filter((x) => x !== id) : [...xs, id]);
  const finish = () => onComplete({ role, interests, targetState: state, barState: state, barNo });

  return (
    <div className="modal-scrim">
      <div className="modal" style={{ maxWidth: 540 }}>
        <div className="m-head" style={{ borderBottom: 0, paddingBottom: 0 }}>
          <div>
            <div className="eyebrow">Welcome to LPE</div>
            <h3 style={{ marginTop: 6 }}>{step === 1 ? "What brings you here?" : step === 2 ? "Topics you care about" : "Bar information"}</h3>
          </div>
        </div>
        <div className="m-body" style={{ paddingTop: 16 }}>
          <div className="ob-steps">
            {[1, 2, 3].map((s) => <span key={s} className={cx("s", step >= s && "done")} />)}
          </div>

          {step === 1 ? (
            <div className="ob-opts">
              {ROLES.map((r) => (
                <button key={r.id} className={cx("ob-opt", role === r.id && "sel")} onClick={() => setRole(r.id)}>
                  <span className="ck">{role === r.id ? <Icon name="check" size={13} /> : null}</span>
                  <span><span style={{ display: "block" }}>{r.id}</span><span style={{ fontSize: 12, fontWeight: 400, color: "var(--grey)" }}>{r.desc}</span></span>
                </button>
              ))}
            </div>
          ) : null}

          {step === 2 ? (
            <>
              <p className="small" style={{ marginBottom: 14 }}>Pick a few — we'll prioritize these in your library and recommendations.</p>
              <div className="ob-opts cols">
                {CATEGORIES.map((c) => (
                  <button key={c.id} className={cx("ob-opt", interests.includes(c.id) && "sel")} onClick={() => toggleInterest(c.id)}>
                    <span className="ck">{interests.includes(c.id) ? <Icon name="check" size={13} /> : null}</span>{c.label}
                  </button>
                ))}
              </div>
            </>
          ) : null}

          {step === 3 ? (
            <>
              <p className="small" style={{ marginBottom: 14 }}>For CLE tracking and certificates. You can skip this and add it later in settings.</p>
              <div className="form-field"><label>Bar jurisdiction</label>
                <select value={state} onChange={(e) => setState(e.target.value)}>{US_STATES.map((s) => <option key={s}>{s}</option>)}</select>
              </div>
              <div className="form-field"><label>Bar number (optional)</label><input value={barNo} onChange={(e) => setBarNo(e.target.value)} placeholder="e.g. OH-0094213" /></div>
            </>
          ) : null}
        </div>
        <div className="m-foot">
          {step > 1 ? <Button variant="ghost" onClick={() => setStep(step - 1)}>Back</Button> : <span />}
          <div style={{ display: "flex", gap: 10, marginLeft: "auto" }}>
            {step === 3 ? <Button variant="ghost" onClick={finish}>Skip</Button> : null}
            {step < 3
              ? <Button variant="primary" iconRight="arrowRight" onClick={() => setStep(step + 1)} disabled={step === 2 && interests.length === 0}>Continue</Button>
              : <Button variant="primary" icon="check" onClick={finish}>Finish setup</Button>}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { SettingsScreen, Onboarding, Switch });
