/* MatchPlan.ai — Settings. Each section tunes the AI that writes your briefs;
   your edits apply to the very next brief you generate. */

const TONE_OPTIONS = ["Consultative", "Direct", "Warm", "Data-driven"];
const CALL_LENGTHS = ["15 min", "25 min", "30 min", "45 min"];

// ---- tag (chip) input ----
function TagInput({ value, onChange, placeholder }) {
  const [draft, setDraft] = React.useState("");
  const add = (t) => {
    const v = t.trim().replace(/,$/, "");
    if (v && value.indexOf(v) === -1) onChange(value.concat(v));
    setDraft("");
  };
  const remove = (i) => onChange(value.filter((_, j) => j !== i));
  return (
    <div className="mp-tags" onClick={(e) => { const inp = e.currentTarget.querySelector("input"); if (inp) inp.focus(); }}>
      {value.map((t, i) => (
        <span key={i} className="mp-tag">{t}
          <button type="button" onClick={(e) => { e.stopPropagation(); remove(i); }} aria-label={"Remove " + t}><Icon name="X" size={12} /></button>
        </span>
      ))}
      <input value={draft} placeholder={value.length ? "Add another…" : placeholder}
        onChange={(e) => setDraft(e.target.value)}
        onKeyDown={(e) => {
          if (e.key === "Enter" || e.key === ",") { e.preventDefault(); add(draft); }
          else if (e.key === "Backspace" && !draft && value.length) remove(value.length - 1);
        }}
        onBlur={() => { if (draft.trim()) add(draft); }} />
    </div>
  );
}

function SettingsSection({ icon, title, help, children }) {
  return (
    <Card>
      <div className="mp-card__pad">
        <div className="mp-setcard__head">
          <span className="mp-section__icon"><Icon name={icon} size={17} /></span>
          <div className="mp-setcard__titles"><h3 className="text-heading-3">{title}</h3></div>
        </div>
        <p className="mp-setcard__help">{help}</p>
        <div className="mp-setcard__body">{children}</div>
      </div>
    </Card>
  );
}

// ---- Sign out ----
// The suite shell (pitchiq #70) has no avatar menu of its own. This is the ONLY
// sign-out affordance at any width, desktop included — same behavior the old
// Sidebar profile menu used
// (nav.jsx's deleted Sidebar: `MP.logout().finally(() => navigate("/login"))`).
//
// It is NOT reached via the avatar any more: since #122 `onOpenAccount` leaves for
// the Suite's account settings whenever the Suite's URL is known. This page stays
// reachable at every width regardless — both nav lists carry `/settings`
// ("Setup" in NAV_ITEMS, "You" in MOBILE_NAV_ITEMS) — so sign-out is not stranded.
function SignOutSection() {
  const signOut = () => {
    if (MP.apiOn) { MP.logout().finally(() => navigate("/login")); }
    else { navigate("/login"); }
  };
  return (
    <SettingsSection icon="LogOut" title="Sign out" help="End your session on this device.">
      <Button variant="secondary" icon="LogOut" onClick={signOut}>Sign out</Button>
    </SettingsSection>
  );
}

function SettingsPage({ path }) {
  const toast = useToast();
  const [s, setS] = React.useState(() => MP.getSettings());
  const [saved, setSaved] = React.useState(() => MP.getSettings());
  const dirty = JSON.stringify(s) !== JSON.stringify(saved);
  const set = (k, v) => setS(prev => ({ ...prev, [k]: v }));
  const field = (k) => (e) => set(k, e.target.value);

  // The spec: "Your name" shows the name on the user's shared Evolve account
  // and is read-only here; name changes happen at the Suite account level.
  // `MP.get().user.name` is that identity — the same one /api/shell reports —
  // whereas MP.getSettings().name is Edge's local override of it.
  const accountName = (MP.get().user && MP.get().user.name) || "";

  const save = async () => {
    // Name is account-owned and read-only here, so it is never taken from
    // local state — otherwise a stale `s.name` would quietly overwrite the
    // shared account name on every save.
    const next = { ...s, name: accountName };
    try {
      await MP.saveSettings(next);
      setSaved(MP.getSettings());
      toast.success("Saved — your next brief uses these.");
    } catch (e) {
      // Local state keeps the edit; only the server write failed.
      toast.error("Couldn't save your changes. Try again.");
    }
  };
  const revert = () => setS(saved);

  return (
    <Shell path={path} width="mp-w-3xl">
      <PageHeader title="Brief Setup"
        eyebrow={<><Icon name="Wand2" size={13} /> Tunes your AI</>}
        subtitle="Everything here is fed straight into the AI that writes your briefs. Edit anything — your next brief uses it instantly."
        back={{ to: "/dashboard", label: "Back to home" }} />

      <div className="mp-fade">
        <div className="mp-set-stack">
          <SettingsSection icon="User" title="You"
            help="Who's walking into the call. Sets the voice and seniority the brief is written for.">
            <div className="mp-grid-2">
              <Field label="Your name"><Input value={accountName} disabled readOnly /></Field>
              <Field label="Your role"><Input value={s.role} onChange={field("role")} placeholder="Senior Account Executive" /></Field>
            </div>
          </SettingsSection>

          <SettingsSection icon="Building2" title="Your company"
            help="What you do and sell, in your own words. Anchors every recommendation to your offering.">
            <Field label="Company name"><Input value={s.company} onChange={field("company")} placeholder="Northbeam" /></Field>
            <Field label="What does your company do?"><Textarea rows={2} value={s.companyDoes} onChange={field("companyDoes")} /></Field>
            <Field label="What do you sell?"><Textarea rows={2} value={s.sells} onChange={field("sells")} /></Field>
          </SettingsSection>

          <SettingsSection icon="Target" title="Ideal customer profile"
            help="Who you sell to. The AI scores every prospect against this to judge fit and flag buying signals.">
            <Field label="Target company size"><Input value={s.sizes} onChange={field("sizes")} placeholder="Mid-market teams, 200–2,000 employees" /></Field>
            <Field label="Industries" hint="Press Enter or comma to add.">
              <TagInput value={s.industries} onChange={(v) => set("industries", v)} placeholder="e.g. B2B SaaS, Fintech" />
            </Field>
            <Field label="Buyer roles" hint="The people you sell to.">
              <TagInput value={s.buyerRoles} onChange={(v) => set("buyerRoles", v)} placeholder="e.g. VP Sales, RevOps" />
            </Field>
            <Field label="Pain points you solve">
              <TagInput value={s.painPoints} onChange={(v) => set("painPoints", v)} placeholder="e.g. manual busywork" />
            </Field>
            <Field label="Buying signals to watch for">
              <TagInput value={s.signals} onChange={(v) => set("signals", v)} placeholder="e.g. Recent funding" />
            </Field>
          </SettingsSection>

          <SettingsSection icon="Megaphone" title="Messaging & positioning"
            help="Your value prop, your edge, and how you beat the competition. Shapes the pitch angles and objection handling.">
            <Field label="Value proposition"><Textarea rows={2} value={s.valueProp} onChange={field("valueProp")} /></Field>
            <Field label="Key differentiator"><Textarea rows={2} value={s.differentiator} onChange={field("differentiator")} /></Field>
            <Field label="Main competitors">
              <TagInput value={s.competitors} onChange={(v) => set("competitors", v)} placeholder="e.g. Incumbent suite" />
            </Field>
            <Field label="How you position against them"><Textarea rows={2} value={s.positioning} onChange={field("positioning")} /></Field>
          </SettingsSection>

          <SettingsSection icon="SlidersHorizontal" title="Brief style"
            help="How you like your briefs written — the AI matches this voice and focus.">
            <Field label="Tone">
              <div className="mp-seg">
                {TONE_OPTIONS.map(t => (
                  <button key={t} type="button" className={s.tone === t ? "is-on" : ""} onClick={() => set("tone", t)}>{t}</button>
                ))}
              </div>
            </Field>
            <div className="mp-grid-2">
              <Field label="Default call length">
                <Select value={s.callLength} onChange={field("callLength")}>
                  {CALL_LENGTHS.map(c => <option key={c} value={c}>{c}</option>)}
                </Select>
              </Field>
            </div>
            <Field label="Emphasize in every brief" hint="What you want the AI to lean on.">
              <TagInput value={s.emphasis} onChange={(v) => set("emphasis", v)} placeholder="e.g. ROI / payback, Security" />
            </Field>
          </SettingsSection>

          <SignOutSection />

          {dirty && (
            <div className="mp-savebar">
              <Card>
                <div className="mp-savebar__msg"><span className="dot"></span> Unsaved changes</div>
                <div style={{ flex: 1 }}></div>
                <Button variant="ghost" size="sm" onClick={revert}>Discard</Button>
                <Button size="sm" icon="Check" onClick={save}>Save changes</Button>
              </Card>
            </div>
          )}
        </div>
      </div>
    </Shell>
  );
}

Object.assign(window, { SettingsPage, TagInput, SettingsSection, SignOutSection, TONE_OPTIONS, CALL_LENGTHS });
