/* settings.jsx — Email template management settings page.
 * Requires: app.jsx (Sidebar, Topbar, I, Avatar, Pill globals)
 *           email-store.jsx (loadTemplateStore, saveTemplateStore, etc.)
 */

/* ── Stage list for the settings page (minus "applied") ─────────────────── */
const ST_STAGE_GROUPS = [
  { id: "intro_screening", label: "Intro screening" },
  { id: "hiring_manager",  label: "Hiring manager" },
  { id: "technical_test",  label: "Technical test" },
  { id: "offer",           label: "Offer" },
  { id: "hired",           label: "Hired" },
  { id: "rejected",        label: "Rejected" },
];

const STAGE_ACCENT = {
  intro_screening: "var(--neutral-50)",
  hiring_manager:  "var(--indigo-50)",
  technical_test:  "var(--violet-50)",
  offer:           "var(--yellow-50)",
  hired:           "var(--green-50)",
  rejected:        "var(--red-50)",
};

/* Sample data used for live preview */
const PREVIEW_CTX = {
  contact: { firstName: "Alex", lastName: "Rivera" },
  posting: { title: "Senior backend engineer", location: "Remote · LatAm" },
  stage: { label: "Intro screening" },
};

/* ── Variable insert chip ─────────────────────────────────────────────────── */
function VarChip({ label, onClick }) {
  return (
    <button
      type="button"
      className="st-var-chip"
      onClick={onClick}
      title={`Insert ${label}`}
    >
      {`{{${label}}}`}
    </button>
  );
}

/* ── TemplateEditor ──────────────────────────────────────────────────────── */
function TemplateEditor({ tpl, bindings, allTemplates, onSave, onDelete }) {
  const { useState, useEffect, useRef } = React;

  const [name,    setName]    = useState(tpl.name || "");
  const [stageId, setStageId] = useState(tpl.stageId || "intro_screening");
  const [subject, setSubject] = useState(tpl.subject || "");
  const [body,    setBody]    = useState(tpl.body    || "");
  const [isDefault, setIsDefault] = useState(false);
  const [showPreview, setShowPreview] = useState(false);

  const bodyRef    = useRef(null);
  const subjectRef = useRef(null);

  useEffect(() => {
    setName(tpl.name || "");
    setStageId(tpl.stageId || "intro_screening");
    setSubject(tpl.subject || "");
    setBody(tpl.body || "");
    setIsDefault(bindings[tpl.stageId] === tpl.id);
  }, [tpl.id]);

  useEffect(() => {
    if (bodyRef.current) {
      bodyRef.current.style.height = "auto";
      bodyRef.current.style.height = bodyRef.current.scrollHeight + "px";
    }
  }, [body]);

  const insertVar = (fieldRef, setter, varName) => {
    const el = fieldRef.current;
    if (!el) return;
    const start = el.selectionStart || 0;
    const end   = el.selectionEnd   || 0;
    const val   = el.value;
    const token = `{{${varName}}}`;
    const next  = val.slice(0, start) + token + val.slice(end);
    setter(next);
    setTimeout(() => {
      el.focus();
      el.setSelectionRange(start + token.length, start + token.length);
    }, 0);
  };

  const preview = showPreview
    ? renderEmailTemplate({ subject, body }, { ...PREVIEW_CTX, stage: { label: ST_STAGE_GROUPS.find(s => s.id === stageId)?.label || "" } })
    : null;

  const VARS = ["firstName", "lastName", "role", "stageName", "recruiter", "recruiterTitle"];

  return (
    <div className="st-editor">
      <div className="st-editor-head">
        <div className="st-editor-title-row">
          <input
            className="st-editor-name-input"
            type="text"
            value={name}
            onChange={(e) => setName(e.target.value)}
            placeholder="Template name"
          />
          <div className="st-editor-head-actions">
            <button
              className={`btn btn-sm ${showPreview ? "btn-brand" : "btn-outline"}`}
              onClick={() => setShowPreview(v => !v)}
            >
              {showPreview ? <I.Check width="13" height="13" /> : <I.Sparkle width="13" height="13" />}
              {showPreview ? "Editing" : "Preview"}
            </button>
            <button
              className="btn btn-outline btn-sm"
              style={{ color: "var(--red-70)", borderColor: "var(--red-30)" }}
              onClick={() => onDelete && onDelete(tpl.id)}
              title="Delete template"
            >
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" width="13" height="13"><path d="M3 6h18M19 6l-1 14H6L5 6M10 11v6M14 11v6M9 6V4h6v2"/></svg>
              Delete
            </button>
          </div>
        </div>

        {/* Stage binding row */}
        <div className="st-editor-meta-row">
          <div className="st-editor-meta-item">
            <span className="st-meta-label">Linked stage</span>
            <select
              className="st-meta-select"
              value={stageId}
              onChange={(e) => setStageId(e.target.value)}
            >
              {ST_STAGE_GROUPS.map(s => (
                <option key={s.id} value={s.id}>{s.label}</option>
              ))}
            </select>
          </div>

          <div className="st-editor-meta-item st-default-toggle">
            <label className="st-toggle-label" htmlFor={`default-${tpl.id}`}>
              <span>Default for {ST_STAGE_GROUPS.find(s => s.id === stageId)?.label}</span>
              <input
                id={`default-${tpl.id}`}
                type="checkbox"
                className="st-toggle-checkbox"
                checked={bindings[stageId] === tpl.id}
                onChange={(e) => {
                  if (e.target.checked) setIsDefault(true);
                  // The save will persist this
                }}
              />
            </label>
          </div>
        </div>
      </div>

      {showPreview ? (
        /* Live preview */
        <div className="st-preview">
          <div className="st-preview-label">Preview with sample data (Alex Rivera → {ST_STAGE_GROUPS.find(s => s.id === stageId)?.label})</div>
          <div className="st-preview-subject">
            <span className="st-preview-field-label">Subject</span>
            <span>{preview.subject}</span>
          </div>
          <div className="st-preview-body">
            <span className="st-preview-field-label">Body</span>
            <pre className="st-preview-pre">{preview.body}</pre>
          </div>
        </div>
      ) : (
        /* Edit form */
        <div className="st-fields">
          {/* Variable chips */}
          <div className="st-vars-row">
            <span className="st-vars-label">Insert variable</span>
            {VARS.map(v => (
              <VarChip key={v} label={v} onClick={() => {
                /* Insert into whichever field was last focused — default body */
                insertVar(bodyRef, setBody, v);
              }} />
            ))}
          </div>

          {/* Subject */}
          <div className="st-field">
            <label className="st-field-label">Subject</label>
            <input
              ref={subjectRef}
              className="st-field-input"
              type="text"
              value={subject}
              onChange={(e) => setSubject(e.target.value)}
              placeholder="Email subject line…"
              onFocus={() => {}}
            />
          </div>

          {/* Body */}
          <div className="st-field">
            <label className="st-field-label">Body</label>
            <textarea
              ref={bodyRef}
              className="st-field-textarea"
              value={body}
              onChange={(e) => setBody(e.target.value)}
              placeholder="Email body…"
              rows={12}
            />
          </div>
        </div>
      )}

      {/* Save footer */}
      <div className="st-editor-footer">
        <span className="st-editor-footer-hint">
          Changes are saved to your browser. Team sync coming soon.
        </span>
        <button
          className="btn btn-brand btn-sm"
          onClick={() => onSave && onSave({
            ...tpl,
            name,
            stageId,
            subject,
            body,
          }, bindings[stageId] !== tpl.id && isDefault ? stageId : null)}
        >
          <I.Check width="13" height="13" />
          Save template
        </button>
      </div>
    </div>
  );
}

/* ── SettingsPage ────────────────────────────────────────────────────────── */

function SettingsPage({ onNav }) {
  const { useState, useCallback, useMemo } = React;

  /* Load store */
  function initStore() {
    const stored = loadTemplateStore();
    return {
      templates: { ...DEFAULT_TEMPLATES, ...(stored?.templates || {}) },
      bindings:  { ...DEFAULT_STAGE_BINDINGS, ...(stored?.bindings || {}) },
    };
  }

  const [store,         setStore]         = useState(initStore);
  const [selectedId,    setSelectedId]    = useState(() => {
    const st = initStore();
    return Object.keys(st.templates)[0] || null;
  });
  const [activeSection, setActiveSection] = useState("templates"); // "templates" | "connectors"

  const persist = useCallback((next) => {
    setStore(next);
    saveTemplateStore(next);
  }, []);

  /* Get the selected template */
  const selectedTpl = selectedId ? store.templates[selectedId] : null;

  /* Group templates by stage */
  const grouped = useMemo(() => {
    const map = {};
    ST_STAGE_GROUPS.forEach(s => { map[s.id] = []; });
    Object.values(store.templates).forEach(t => {
      if (map[t.stageId]) map[t.stageId].push(t);
      else map["intro_screening"].push(t);
    });
    return map;
  }, [store.templates]);

  /* Handlers */
  const handleSave = useCallback((updatedTpl, makeDefaultForStage) => {
    const next = {
      templates: { ...store.templates, [updatedTpl.id]: updatedTpl },
      bindings:  { ...store.bindings },
    };
    if (makeDefaultForStage) {
      next.bindings[makeDefaultForStage] = updatedTpl.id;
    }
    persist(next);
  }, [store, persist]);

  const handleDelete = useCallback((tplId) => {
    if (!window.confirm("Delete this template? This cannot be undone.")) return;
    const nextTemplates = { ...store.templates };
    delete nextTemplates[tplId];
    const nextBindings = { ...store.bindings };
    Object.entries(nextBindings).forEach(([stageId, id]) => {
      if (id === tplId) delete nextBindings[stageId];
    });
    const next = { templates: nextTemplates, bindings: nextBindings };
    persist(next);
    const remaining = Object.keys(nextTemplates);
    setSelectedId(remaining[0] || null);
  }, [store, persist]);

  const handleNewTemplate = useCallback(() => {
    const id  = newTemplateId();
    const tpl = {
      id,
      name:    "New template",
      stageId: "intro_screening",
      subject: "Hello {{firstName}}",
      body:    "Hi {{firstName}},\n\nYour message here.\n\nBest,\n{{recruiter}}\n{{recruiterTitle}}",
    };
    const next = { ...store, templates: { ...store.templates, [id]: tpl } };
    persist(next);
    setSelectedId(id);
  }, [store, persist]);

  const handleResetToDefaults = useCallback(() => {
    if (!window.confirm("Reset all templates to Airtm defaults? Custom templates will be lost.")) return;
    resetTemplateStore();
    const fresh = initStore();
    setStore(fresh);
    setSelectedId(Object.keys(fresh.templates)[0] || null);
  }, []);

  return (
    <div style={{
      display: "flex", height: "100%",
      background: "var(--bg-secondary)", position: "relative"
    }}>
      <Sidebar active="settings" onNav={onNav} />

      <div style={{ flex: 1, display: "flex", flexDirection: "column", minWidth: 0 }}>
        <Topbar title="Settings" onSearch={() => {}} onSettings={() => {}} />

        <div style={{ flex: 1, overflow: "auto" }}>
          <div style={{ maxWidth: 1200, margin: "0 auto", padding: "28px 32px 48px" }}>

            {/* page header */}
            <div style={{ marginBottom: 24 }}>
              <div style={{ fontSize: 13, color: "var(--content-tertiary)", marginBottom: 4 }}>
                <button onClick={() => onNav && onNav("dashboard")} style={{
                  background: "none", border: 0, padding: 0, font: "inherit",
                  color: "var(--content-tertiary)", cursor: "pointer",
                }}>Dashboard</button>
                {" / "}
                <span style={{ color: "var(--content-primary)", fontWeight: 600 }}>Settings</span>
              </div>
              <h2 style={{ margin: 0, fontSize: 26, fontWeight: 600, letterSpacing: "-0.01em" }}>Settings</h2>
              <div style={{ fontSize: 13, color: "var(--content-tertiary)", marginTop: 4 }}>
                Manage email templates and ATS configuration.
              </div>
            </div>

            {/* section tabs */}
            <div style={{ display: "flex", gap: 4, marginBottom: 20,
              borderBottom: "1px solid var(--stroke-secondary)", paddingBottom: 0 }}>
              {[{ id: "templates", label: "Email templates" }, { id: "connectors", label: "Connectors" }].map(tab => (
                <button key={tab.id} onClick={() => setActiveSection(tab.id)} style={{
                  padding: "10px 16px", border: 0, background: "none", cursor: "pointer",
                  fontFamily: "var(--font-sans)", fontWeight: 600, fontSize: 13,
                  color: activeSection === tab.id ? "var(--content-primary)" : "var(--content-tertiary)",
                  borderBottom: activeSection === tab.id
                    ? "2px solid var(--indigo-50)"
                    : "2px solid transparent",
                  marginBottom: -1,
                }}>{tab.label}</button>
              ))}
            </div>

            {/* ── Templates section ── */}
            {activeSection === "templates" && (
              <div className="st-layout">
                {/* left: template list */}
                <div className="st-sidebar">
                  <div className="st-sidebar-head">
                    <span className="st-sidebar-title">Templates</span>
                    <button className="btn btn-outline btn-sm" onClick={handleNewTemplate}>
                      <I.Plus width="12" height="12" />
                      New
                    </button>
                  </div>

                  {ST_STAGE_GROUPS.map(stage => {
                    const tpls = grouped[stage.id] || [];
                    if (tpls.length === 0) return null;
                    return (
                      <div key={stage.id} className="st-stage-group">
                        <div className="st-stage-group-label">
                          <span className="st-stage-dot" style={{ background: STAGE_ACCENT[stage.id] }} />
                          {stage.label}
                        </div>
                        {tpls.map(t => (
                          <button
                            key={t.id}
                            className={`st-tpl-row${selectedId === t.id ? " st-tpl-row--active" : ""}`}
                            onClick={() => setSelectedId(t.id)}
                          >
                            <span className="st-tpl-name">{t.name}</span>
                            {store.bindings[t.stageId] === t.id && (
                              <span className="st-tpl-default-badge">default</span>
                            )}
                          </button>
                        ))}
                      </div>
                    );
                  })}

                  <div className="st-sidebar-footer">
                    <button
                      className="btn btn-link btn-sm"
                      style={{ fontSize: 12, color: "var(--content-tertiary)" }}
                      onClick={handleResetToDefaults}
                    >
                      Reset to defaults
                    </button>
                  </div>
                </div>

                {/* right: editor */}
                <div className="st-editor-wrap">
                  {selectedTpl ? (
                    <TemplateEditor
                      key={selectedTpl.id}
                      tpl={selectedTpl}
                      bindings={store.bindings}
                      allTemplates={store.templates}
                      onSave={handleSave}
                      onDelete={handleDelete}
                    />
                  ) : (
                    <div className="st-editor-empty">
                      <I.Send width="28" height="28" style={{ color: "var(--content-tertiary)", opacity: 0.5 }} />
                      <div>Select a template from the list, or create a new one.</div>
                    </div>
                  )}
                </div>
              </div>
            )}

            {/* ── Connectors section ── */}
            {activeSection === "connectors" && (
              <div style={{ maxWidth: 600 }}>
                <div style={{ background: "var(--bg-primary)", borderRadius: 14,
                  border: "1px solid var(--stroke-secondary)", overflow: "hidden" }}>
                  {/* in-house DB */}
                  <div style={{ padding: "16px 20px", display: "flex", alignItems: "center",
                    gap: 16, borderBottom: "1px solid var(--stroke-secondary)" }}>
                    <div style={{ width: 40, height: 40, borderRadius: 10,
                      background: "var(--green-10)", display: "flex", alignItems: "center",
                      justifyContent: "center", fontWeight: 700, fontSize: 14,
                      color: "var(--green-70)" }}>DB</div>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontWeight: 600, fontSize: 14 }}>In-house DB</div>
                      <div style={{ fontSize: 12, color: "var(--content-tertiary)" }}>
                        PostgreSQL on RDS · live data
                      </div>
                    </div>
                    <Pill tone="prog" dot>Connected</Pill>
                  </div>

                  {/* other connectors */}
                  {["Greenhouse", "Workable", "Ashby", "CSV import"].map(name => (
                    <div key={name} style={{ padding: "16px 20px", display: "flex",
                      alignItems: "center", gap: 16,
                      borderBottom: "1px solid var(--stroke-secondary)" }}>
                      <div style={{ width: 40, height: 40, borderRadius: 10,
                        background: "var(--bg-secondary)", display: "flex", alignItems: "center",
                        justifyContent: "center", fontWeight: 700, fontSize: 14,
                        color: "var(--content-primary)" }}>{name[0]}</div>
                      <div style={{ flex: 1 }}>
                        <div style={{ fontWeight: 600, fontSize: 14 }}>{name}</div>
                        <div style={{ fontSize: 12, color: "var(--content-tertiary)" }}>
                          One-click connect
                        </div>
                      </div>
                      <button className="btn btn-outline btn-sm">Connect →</button>
                    </div>
                  ))}
                </div>

                {/* AI model card */}
                <div style={{ marginTop: 20, padding: "16px 20px",
                  background: "var(--bg-primary)", borderRadius: 14,
                  border: "1px solid var(--stroke-secondary)",
                  display: "flex", alignItems: "center", gap: 16 }}>
                  <I.Sparkle width="22" height="22" style={{ color: "var(--indigo-50)", flexShrink: 0 }} />
                  <div style={{ flex: 1 }}>
                    <div style={{ fontWeight: 600, fontSize: 14 }}>Airtm Rank v2 · trained on 142k hires</div>
                    <div style={{ fontSize: 12, color: "var(--content-tertiary)", marginTop: 2 }}>
                      Calibrated weekly · 84% precision@10 over the last 90 days
                    </div>
                  </div>
                  <Pill tone="brand">Active</Pill>
                </div>
              </div>
            )}

          </div>
        </div>
      </div>
    </div>
  );
}

window.SettingsPage = SettingsPage;
