// Kayser v2 — MVP additions
// 1. Memory sheet: visible USER + MEMORY (Hermes-style), editable
// 2. Expanded approval card sheet: reasoning, editable draft, alternatives
// 3. "Don't do that again" correction sheet for auto-handled cards
// 4. Floating undo bar after a real send
// 5. New palette items wired to memory + skills

// ============ MEMORY DATA (mirrors Hermes USER.md / MEMORY.md) ============
const KXV2_USER_PROFILE = [
  { id: 'u1', text: "Wes Kayser, owner of Kayser Foundation Repair, Fort Worth TX.", pinned: true },
  { id: 'u2', text: "Prefers short replies. Hates fluff. 'Just tell me what you did.'" },
  { id: 'u3', text: "Texts > calls > email. Will answer texts on the road, ignores email until evening." },
  { id: 'u4', text: "Tone with customers: warm but direct. Never apologetic. Signs off 'Wes'." },
  { id: 'u5', text: "Schedule: on site 7am–4pm, office 4–6pm. Don't ping after 7pm unless urgent." },
];

const KXV2_AGENT_MEMORY = [
  { id: 'm1', text: "Garcia (Lina) usually pays day 5. Past 7 days = nudge, not panic. Husband Mateo decides on price.", learned: '3 weeks ago' },
  { id: 'm2', text: "Crew B leaves the yard 15 min before scheduled start. Don't ping them too early.", learned: '2 weeks ago' },
  { id: 'm3', text: "Weather reschedules: auto if forecast >60% rain on exterior work, ask for everything else.", learned: '6 days ago' },
  { id: 'm4', text: "Wes likes to hand-write quotes over $15K. Don't auto-send those.", learned: '5 days ago' },
  { id: 'm5', text: "Sherwin Williams receipts always go to job 1822 unless noted otherwise.", learned: '4 days ago' },
  { id: 'm6', text: "Don't draft collections calls — only texts. Wes does the calls himself.", learned: '2 days ago', recent: true },
];

// ============ MEMORY SHEET ============
function KxV2MemorySheet({ open, onClose }) {
  const [tab, setTab] = React.useState('user');
  const [editing, setEditing] = React.useState(null);
  const [draftText, setDraftText] = React.useState('');
  const [adding, setAdding] = React.useState(false);
  const [newFact, setNewFact] = React.useState('');
  // Live mode populates these from /api/v1/memory; prototype mode keeps
  // the mock arrays so the standalone demo still shows realistic copy.
  const live = !!window.KX_TOKEN;
  const [userList,  setUserList]  = React.useState(live ? [] : KXV2_USER_PROFILE);
  const [agentList, setAgentList] = React.useState(live ? [] : KXV2_AGENT_MEMORY);
  // Hermes-enforced char ceilings — defaults match the constants in
  // atlas-api's memory_files.py but get overwritten from the server
  // payload on each fetch so we stay in sync if Hermes ever changes them.
  const [userMax,   setUserMax]   = React.useState(1375);
  const [agentMax,  setAgentMax]  = React.useState(2200);

  React.useEffect(() => {
    if (!open) return;
    setEditing(null); setAdding(false); setNewFact('');
    // Re-fetch on every open so the sheet always reflects what the agent
    // has written since the last view. Best-effort — on failure we leave
    // whatever's already in state.
    if (!live || !window.kxApi) return;
    (async () => {
      try {
        const data = await window.kxApi('/memory');
        // Server returns `memory: list[str]` (agent notes) and
        // `user: list[str]` (operator profile). The renderer wants
        // `[{id, text}]` so we wrap with a stable index-based id.
        const wrap = (arr, prefix) =>
          (arr || []).map((text, i) => ({ id: prefix + i, text }));
        setUserList(wrap(data?.user, 'u'));
        setAgentList(wrap(data?.memory, 'm'));
        if (typeof data?.user_max   === 'number') setUserMax(data.user_max);
        if (typeof data?.memory_max === 'number') setAgentMax(data.memory_max);
      } catch (_) { /* best-effort; kxApi handles 401 redirect */ }
    })();
  }, [open, live]);

  const list = tab === 'user' ? userList : agentList;
  const setList = tab === 'user' ? setUserList : setAgentList;
  const userBytes  = userList.reduce((n, e) => n + e.text.length, 0);
  const agentBytes = agentList.reduce((n, e) => n + e.text.length, 0);

  // In live mode the memory tool is owned by Hermes — POST /memory is a
  // no-op stub (see atlas-api/v1.py). Local edits would just snap back
  // on next fetch and we'd be lying to the user. Hide the edit/forget/
  // add affordances and show a clear "ask in chat" hint instead.
  const editable = !live;
  const startEdit = (e) => { setEditing(e.id); setDraftText(e.text); };
  const saveEdit = () => {
    setList(list.map(e => e.id === editing ? { ...e, text: draftText } : e));
    setEditing(null);
  };
  const forget = (id) => setList(list.filter(e => e.id !== id));
  const addFact = () => {
    if (!newFact.trim()) return;
    setList([...list, { id: 'n' + Date.now(), text: newFact.trim(), recent: true }]);
    setNewFact(''); setAdding(false);
  };

  return (
    <KxV2Sheet open={open} onClose={onClose} title="What I know about you">
      <div style={{ padding: '8px 14px 4px', display: 'flex', gap: 6 }}>
        {[
          { k: 'user',  label: 'You',     pct: Math.round(userBytes / userMax  * 100), max: userMax,  used: userBytes, n: userList.length },
          { k: 'agent', label: 'My notes', pct: Math.round(agentBytes / agentMax * 100), max: agentMax, used: agentBytes, n: agentList.length },
        ].map(s => (
          <button key={s.k} onClick={() => setTab(s.k)} style={{
            flex: 1, padding: '10px 10px', borderRadius: 12,
            background: tab === s.k ? KX2.chipBgActive : KX2.chipBg,
            border: `1px solid ${tab === s.k ? KX2.brand : KX2.glassLine}`,
            cursor: 'pointer', textAlign: 'left',
          }}>
            <div style={{ fontSize: 12.5, fontWeight: 600, color: KX2.ink, fontFamily: KX2.fontUI }}>{s.label}</div>
            <div style={{ fontSize: 10, color: KX2.ink3, marginTop: 2, fontFamily: KX2.fontMono }}>
              {s.n} entries · {s.used}/{s.max} chars
            </div>
            <div style={{ marginTop: 5, height: 2, borderRadius: 1, background: 'rgba(255,255,255,.08)', overflow: 'hidden' }}>
              <div style={{ width: `${s.pct}%`, height: '100%', background: s.pct > 80 ? KX2.warn : KX2.brand }} />
            </div>
          </button>
        ))}
      </div>

      <div style={{ padding: '8px 14px 12px', fontSize: 11.5, color: KX2.ink3, lineHeight: 1.45 }}>
        {tab === 'user'
          ? (live
              ? "How you like to work. I read this every time we talk. To change something, just tell me in chat."
              : "How you like to work. I read this every time we talk.")
          : (live
              ? "What I've learned about your business. I edit this myself as I learn — to add or correct something, tell me in chat."
              : "What I've learned about your business. I edit this myself as I learn — you can correct anything.")}
      </div>

      {live && list.length === 0 && (
        <div style={{ padding: '20px 18px', textAlign: 'center', color: KX2.ink3, fontSize: 12.5, lineHeight: 1.5 }}>
          {tab === 'user'
            ? "Nothing here yet. I'll start learning how you like to work as we chat."
            : "Nothing here yet. I'll save useful facts about your business as I pick them up."}
        </div>
      )}

      <div style={{ padding: '0 12px 16px', display: 'grid', gap: 6 }}>
        {list.map(e => (
          <div key={e.id} style={{
            ...kx2GlassThin({ borderRadius: 10 }),
            padding: '10px 12px',
            border: e.recent ? `1px solid ${KX2.brand}` : `1px solid ${KX2.glassLine}`,
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4 }}>
              {e.pinned && <span style={{ fontFamily: KX2.fontMono, fontSize: 9, color: KX2.warn, letterSpacing: 0.4 }}>◆ PINNED</span>}
              {e.recent && <span style={{ fontFamily: KX2.fontMono, fontSize: 9, color: KX2.brand, letterSpacing: 0.4 }}>NEW</span>}
              {e.learned && <span style={{ fontFamily: KX2.fontMono, fontSize: 9.5, color: KX2.ink3, letterSpacing: 0.3 }}>learned {e.learned}</span>}
              <span style={{ flex: 1 }} />
              {editable && editing === e.id && (
                <>
                  <button onClick={saveEdit} style={{
                    background: 'transparent', border: 'none', color: KX2.brand,
                    fontFamily: KX2.fontMono, fontSize: 10, fontWeight: 700, cursor: 'pointer', padding: 2,
                  }}>save</button>
                  <button onClick={() => setEditing(null)} style={{
                    background: 'transparent', border: 'none', color: KX2.ink3,
                    fontFamily: KX2.fontMono, fontSize: 10, cursor: 'pointer', padding: 2,
                  }}>cancel</button>
                </>
              )}
              {editable && editing !== e.id && (
                <>
                  <button onClick={() => startEdit(e)} style={{
                    background: 'transparent', border: 'none', color: KX2.ink3,
                    fontFamily: KX2.fontMono, fontSize: 10, cursor: 'pointer', padding: 2,
                  }}>edit</button>
                  <button onClick={() => forget(e.id)} style={{
                    background: 'transparent', border: 'none', color: KX2.reject,
                    fontFamily: KX2.fontMono, fontSize: 10, cursor: 'pointer', padding: 2,
                  }}>forget</button>
                </>
              )}
            </div>
            {editing === e.id ? (
              <textarea value={draftText} onChange={(ev) => setDraftText(ev.target.value)} rows={2} autoFocus style={{
                width: '100%', boxSizing: 'border-box', background: 'transparent',
                border: `1px solid ${KX2.brand}`, borderRadius: 6, padding: 6,
                color: KX2.ink, fontSize: 13, fontFamily: KX2.fontUI, lineHeight: 1.45,
                outline: 'none', resize: 'none',
              }} />
            ) : (
              <div style={{ fontSize: 13, color: KX2.ink, lineHeight: 1.45, fontFamily: KX2.fontUI }}>{e.text}</div>
            )}
          </div>
        ))}
      </div>

      <div style={{ padding: '0 14px 18px', display: editable ? 'block' : 'none' }}>
        {adding ? (
          <div style={{ ...kx2GlassThin({ borderRadius: 12 }), padding: 8 }}>
            <textarea value={newFact} onChange={(ev) => setNewFact(ev.target.value)} rows={2} autoFocus
              placeholder={tab === 'user' ? 'e.g. I prefer left-aligned text on quotes' : 'e.g. Vendor "ABC" always invoices on the 15th'}
              style={{
                width: '100%', boxSizing: 'border-box', background: 'transparent',
                border: 'none', outline: 'none', resize: 'none',
                color: KX2.ink, fontSize: 13, fontFamily: KX2.fontUI, lineHeight: 1.45,
                padding: 6,
              }} />
            <div style={{ display: 'flex', gap: 6, marginTop: 4 }}>
              <button onClick={addFact} style={{
                flex: 1, padding: '7px 10px', borderRadius: 8, background: KX2.brand,
                color: '#fff', border: 'none', fontWeight: 600, fontSize: 12, cursor: 'pointer',
              }}>Add</button>
              <button onClick={() => { setAdding(false); setNewFact(''); }} style={{
                padding: '7px 12px', borderRadius: 8, background: KX2.chipBg,
                color: KX2.ink, border: `1px solid ${KX2.glassLine}`, fontSize: 12, cursor: 'pointer',
              }}>Cancel</button>
            </div>
          </div>
        ) : (
          <button onClick={() => setAdding(true)} style={{
            width: '100%', padding: '10px 12px', borderRadius: 12,
            background: KX2.chipBg, color: KX2.ink, border: `1px dashed ${KX2.glassLine}`,
            fontSize: 13, fontFamily: KX2.fontUI, cursor: 'pointer',
          }}>+ Add a fact</button>
        )}
      </div>
    </KxV2Sheet>
  );
}

// ============ EXPANDED APPROVAL SHEET ============
const KXV2_APPROVAL_DETAIL = {
  reasoning: [
    { label: 'Garcia\'s pattern', text: "Pays day 5 of 7 invoices on file. Today is day 7 — first time past 5." },
    { label: 'Why now', text: "She always reads texts within 30 min during business hours. Best window is now." },
    { label: 'Why not call', text: "You told me 'don't draft collections calls' on the 26th. Sticking to text." },
  ],
  draft: 'Hi Maria — just a friendly nudge on invoice #1031 ($4,800). Let me know if you\'d like to set up a payment plan.',
  alternatives: [
    { label: 'Softer tone',   text: 'Hey Maria, hope you\'re doing well. Whenever you get a chance, want to take a look at invoice #1031? No rush — let me know if you have questions.' },
    { label: 'Payment plan',  text: 'Hi Maria — checking in on #1031 ($4,800). Happy to break it into two payments if that\'s easier. Just say the word.' },
    { label: 'Shorter',       text: 'Quick nudge on #1031, Maria. Let me know.' },
  ],
  ifIdoNothing: "I'll ask again in 24 hours, then escalate to a phone-call reminder for you.",
};

// Phase 5.0 — KxV2ApprovalSheet renders in two modes:
//   * Live mode (detail.tool_name + detail.preview present): real
//     approval from the WS approval-pending envelope. Shows the
//     command + tool name + Haiku's rationale. Buttons POST to
//     /api/v1/approvals/{id}/resolve via the onSent/onWrong callbacks.
//   * Prototype mode (no detail prop, or detail without tool_name):
//     legacy Garcia/Lina mock flow. Same callbacks, no real upstream.
function KxV2ApprovalSheet({ open, onClose, onSent, onWrong, onHold, detail }) {
  const isLive = !!(detail && detail.tool_name);
  // Editable draft used only in prototype mode (operator can tweak
  // the suggested text-to-customer). In live mode the agent is asking
  // about a SHELL COMMAND so there's nothing to edit.
  const [draft, setDraft] = React.useState(KXV2_APPROVAL_DETAIL.draft);
  const [showAlts, setShowAlts] = React.useState(false);
  const [showHold, setShowHold] = React.useState(false);

  React.useEffect(() => {
    if (open) {
      setDraft(KXV2_APPROVAL_DETAIL.draft);
      setShowAlts(false);
      setShowHold(false);
    }
  }, [open]);

  if (isLive) {
    // Render the live (real-Hermes-approval) shape. Title shows the
    // tool name; body shows the command + Haiku's rationale; actions
    // map directly to Hermes's once/session/always/deny semantics.
    const command = detail.args?.command || detail.args?.cmd || '';
    return (
      <KxV2Sheet open={open} onClose={onClose}
        title={`Approve ${detail.tool_name} action`}>
        <div style={{ padding: '12px 14px 18px' }}>
          {/* Tool summary */}
          <div style={{
            ...kx2GlassThin({ borderRadius: 10 }),
            padding: '10px 12px', display: 'flex', gap: 10, alignItems: 'center',
          }}>
            <div style={{
              width: 36, height: 36, borderRadius: 18, background: KX2.warn,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              color: '#3b2300', fontWeight: 700, fontSize: 13,
            }}>⚡</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13.5, fontWeight: 600, color: KX2.ink }}>
                The agent wants to run {detail.tool_name}
              </div>
              <div style={{ fontSize: 11, color: KX2.ink3, marginTop: 1, fontFamily: KX2.fontMono }}>
                Haiku flagged this for your review · {detail.run_id?.slice(0, 8)}…
              </div>
            </div>
            <span style={{ fontFamily: KX2.fontMono, fontSize: 10, color: KX2.warn, letterSpacing: 0.4 }}>
              NEEDS OK
            </span>
          </div>

          {/* The actual command */}
          {command && (
            <div style={{ marginTop: 14 }}>
              <div style={{
                fontFamily: KX2.fontMono, fontSize: 10, color: KX2.ink3,
                letterSpacing: 0.6, textTransform: 'uppercase', marginBottom: 6,
              }}>Command</div>
              <pre style={{
                ...kx2GlassThin({ borderRadius: 10 }),
                padding: '10px 12px', margin: 0, color: KX2.ink,
                fontFamily: KX2.fontMono, fontSize: 12.5, lineHeight: 1.45,
                whiteSpace: 'pre-wrap', wordBreak: 'break-word',
              }}>{command}</pre>
            </div>
          )}

          {/* Haiku's rationale */}
          {detail.preview && (
            <div style={{
              ...kx2GlassThin({ borderRadius: 10 }),
              padding: '8px 12px', marginTop: 14, fontSize: 12.5, color: KX2.ink2,
              lineHeight: 1.45,
            }}>
              <span style={{
                fontFamily: KX2.fontMono, fontSize: 9.5, letterSpacing: 0.4,
                color: KX2.ink3,
              }}>WHY · </span>
              {detail.preview}
            </div>
          )}

          {/* Actions: Send=once, Hold=client-side-park, Skip=deny */}
          <div style={{ display: 'flex', gap: 6, marginTop: 16 }}>
            <button onClick={onSent} style={{
              flex: 2, padding: '11px 12px', borderRadius: 12, background: KX2.brand,
              color: '#fff', border: 'none', fontWeight: 600, fontSize: 14, cursor: 'pointer',
              boxShadow: '0 6px 18px rgba(124,58,237,.4)',
            }}>Approve · run it</button>
            <button onClick={() => setShowHold(s => !s)} style={{
              flex: 1, padding: '11px 12px', borderRadius: 12,
              background: showHold ? KX2.brandSoft : KX2.chipBg,
              color: KX2.ink, border: `1px solid ${showHold ? KX2.brand : KX2.glassLine}`,
              fontSize: 13, cursor: 'pointer', fontFamily: KX2.fontUI, fontWeight: 600,
            }}>Hold</button>
            <button onClick={onClose} style={{
              flex: 1, padding: '11px 12px', borderRadius: 12, background: KX2.chipBg,
              color: KX2.ink, border: `1px solid ${KX2.glassLine}`, fontSize: 13, cursor: 'pointer',
            }}>Skip</button>
          </div>

          {showHold && (
            <KxV2HoldForReview onSchedule={(minutes) => {
              setShowHold(false);
              onHold?.({ minutes, command });
            }} />
          )}

          <div style={{ marginTop: 14 }}>
            <button onClick={onWrong} style={{
              width: '100%', padding: '9px 12px', borderRadius: 10, background: 'transparent',
              color: KX2.reject, border: `1px solid ${KX2.glassLine}`, fontSize: 12.5, cursor: 'pointer',
              fontFamily: KX2.fontUI,
            }}>Deny + don't ask me again for this command</button>
          </div>
        </div>
      </KxV2Sheet>
    );
  }

  // ── Prototype mode (legacy Garcia/Lina mock) ────────────────────
  return (
    <KxV2Sheet open={open} onClose={onClose} title="Send reminder · Garcia">
      <div style={{ padding: '12px 14px 18px' }}>
        {/* Customer summary */}
        <div style={{ ...kx2GlassThin({ borderRadius: 10 }), padding: '10px 12px', display: 'flex', gap: 10, alignItems: 'center' }}>
          <div style={{ width: 36, height: 36, borderRadius: 18, background: KX2.brandSoft, color: KX2.brand,
            display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 700, fontSize: 13 }}>LG</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 13.5, fontWeight: 600, color: KX2.ink }}>Lina Garcia</div>
            <div style={{ fontSize: 11, color: KX2.ink3, marginTop: 1, fontFamily: KX2.fontMono }}>#1031 · $4,800 · 7 days · LTV $18.2K</div>
          </div>
          <span style={{ fontFamily: KX2.fontMono, fontSize: 10, color: KX2.warn, letterSpacing: 0.4 }}>OVERDUE</span>
        </div>

        {/* Why I'm asking */}
        <div style={{ marginTop: 14 }}>
          <div style={{ fontFamily: KX2.fontMono, fontSize: 10, color: KX2.ink3, letterSpacing: 0.6, textTransform: 'uppercase', marginBottom: 6 }}>Why I'm asking</div>
          <div style={{ display: 'grid', gap: 6 }}>
            {KXV2_APPROVAL_DETAIL.reasoning.map((r, i) => (
              <div key={i} style={{ display: 'flex', gap: 10, padding: '4px 2px' }}>
                <div style={{ width: 5, height: 5, borderRadius: 3, background: KX2.brand, marginTop: 7, flexShrink: 0 }} />
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 12, fontWeight: 600, color: KX2.ink2 }}>{r.label}</div>
                  <div style={{ fontSize: 12.5, color: KX2.ink2, lineHeight: 1.45, marginTop: 1 }}>{r.text}</div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Editable draft */}
        <div style={{ marginTop: 16 }}>
          <div style={{ display: 'flex', alignItems: 'center', marginBottom: 6 }}>
            <span style={{ fontFamily: KX2.fontMono, fontSize: 10, color: KX2.ink3, letterSpacing: 0.6, textTransform: 'uppercase' }}>Draft · text to Lina</span>
            <span style={{ flex: 1 }} />
            <button onClick={() => setShowAlts(s => !s)} style={{
              background: 'transparent', border: 'none', color: KX2.brand,
              fontFamily: KX2.fontMono, fontSize: 10, cursor: 'pointer',
            }}>{showAlts ? 'hide' : 'try another tone'}</button>
          </div>
          <textarea value={draft} onChange={(e) => setDraft(e.target.value)} rows={4} style={{
            width: '100%', boxSizing: 'border-box',
            ...kx2GlassThin({ borderRadius: 10 }),
            padding: '10px 12px', color: KX2.ink, fontSize: 13.5, lineHeight: 1.5,
            fontFamily: KX2.fontUI, resize: 'none', outline: 'none',
          }} />

          {showAlts && (
            <div style={{ marginTop: 8, display: 'grid', gap: 6 }}>
              {KXV2_APPROVAL_DETAIL.alternatives.map((a, i) => (
                <button key={i} onClick={() => { setDraft(a.text); setShowAlts(false); }} style={{
                  textAlign: 'left', padding: '8px 12px', borderRadius: 10,
                  background: 'transparent', border: `1px dashed ${KX2.glassLine}`,
                  cursor: 'pointer', color: KX2.ink2,
                }}>
                  <div style={{ fontFamily: KX2.fontMono, fontSize: 9.5, color: KX2.brand, letterSpacing: 0.5, textTransform: 'uppercase', marginBottom: 3 }}>{a.label}</div>
                  <div style={{ fontSize: 12, lineHeight: 1.45 }}>{a.text}</div>
                </button>
              ))}
            </div>
          )}
        </div>

        {/* If I do nothing */}
        <div style={{ ...kx2GlassThin({ borderRadius: 10 }), padding: '8px 12px', marginTop: 14, fontSize: 12, color: KX2.ink3, lineHeight: 1.45 }}>
          <span style={{ fontFamily: KX2.fontMono, fontSize: 9.5, letterSpacing: 0.4, color: KX2.ink3 }}>IF YOU DO NOTHING · </span>
          {KXV2_APPROVAL_DETAIL.ifIdoNothing}
        </div>

        {/* Actions */}
        <div style={{ display: 'flex', gap: 6, marginTop: 16 }}>
          <button onClick={onSent} style={{
            flex: 2, padding: '11px 12px', borderRadius: 12, background: KX2.brand,
            color: '#fff', border: 'none', fontWeight: 600, fontSize: 14, cursor: 'pointer',
            boxShadow: '0 6px 18px rgba(124,58,237,.4)',
          }}>Send to Lina</button>
          <button onClick={() => setShowHold(s => !s)} style={{
            flex: 1, padding: '11px 12px', borderRadius: 12,
            background: showHold ? KX2.brandSoft : KX2.chipBg,
            color: KX2.ink, border: `1px solid ${showHold ? KX2.brand : KX2.glassLine}`,
            fontSize: 13, cursor: 'pointer', fontFamily: KX2.fontUI, fontWeight: 600,
          }}>Hold</button>
          <button style={{
            flex: 1, padding: '11px 12px', borderRadius: 12, background: KX2.chipBg,
            color: KX2.ink, border: `1px solid ${KX2.glassLine}`, fontSize: 13, cursor: 'pointer',
          }}>Skip</button>
        </div>

        {showHold && (
          <KxV2HoldForReview onSchedule={(minutes) => {
            setShowHold(false);
            onHold?.({ minutes, draft });
          }} />
        )}

        <div style={{ marginTop: 14 }}>
          <button onClick={onWrong} style={{
            width: '100%', padding: '9px 12px', borderRadius: 10, background: 'transparent',
            color: KX2.reject, border: `1px solid ${KX2.glassLine}`, fontSize: 12.5, cursor: 'pointer',
            fontFamily: KX2.fontUI,
          }}>Don't ask me again</button>
        </div>
      </div>
    </KxV2Sheet>
  );
}

// ============ "DON'T DO THAT AGAIN" CORRECTION SHEET ============
function KxV2WrongSheet({ open, onClose, onConfirm }) {
  const [why, setWhy] = React.useState('tone');
  const [note, setNote] = React.useState('');
  const reasons = [
    { k: 'tone',    label: 'Wrong tone' },
    { k: 'time',    label: 'Wrong time' },
    { k: 'person',  label: 'Wrong person' },
    { k: 'never',   label: 'Never do this' },
  ];

  return (
    <KxV2Sheet open={open} onClose={onClose} title="Tell me what was off">
      <div style={{ padding: '12px 14px 18px' }}>
        <div style={{ fontSize: 13, color: KX2.ink2, lineHeight: 1.5, marginBottom: 12 }}>
          I'll undo it and remember not to do it that way again. The more you tell me, the less I'll bug you.
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6 }}>
          {reasons.map(r => (
            <button key={r.k} onClick={() => setWhy(r.k)} style={{
              padding: '10px', borderRadius: 10, cursor: 'pointer',
              background: why === r.k ? KX2.brandSoft : KX2.chipBg,
              border: `1px solid ${why === r.k ? KX2.brand : KX2.glassLine}`,
              color: KX2.ink, fontSize: 13, fontFamily: KX2.fontUI,
            }}>{r.label}</button>
          ))}
        </div>

        <div style={{ marginTop: 14 }}>
          <div style={{ fontFamily: KX2.fontMono, fontSize: 10, color: KX2.ink3, letterSpacing: 0.6, textTransform: 'uppercase', marginBottom: 6 }}>What should I have done? (optional)</div>
          <textarea value={note} onChange={(e) => setNote(e.target.value)} rows={3} placeholder="e.g. 'wait until after 9am' or 'use her first name only'"
            style={{
              width: '100%', boxSizing: 'border-box',
              ...kx2GlassThin({ borderRadius: 10 }),
              padding: '10px 12px', color: KX2.ink, fontSize: 13, lineHeight: 1.45,
              fontFamily: KX2.fontUI, resize: 'none', outline: 'none',
            }} />
        </div>

        <div style={{ ...kx2GlassThin({ borderRadius: 10 }), padding: '10px 12px', marginTop: 14, fontSize: 12, color: KX2.ink2, lineHeight: 1.5 }}>
          <span style={{ fontFamily: KX2.fontMono, fontSize: 9.5, letterSpacing: 0.4, color: KX2.brand }}>I'LL ALSO · </span>
          Lower confidence on this automation by 15% so I'll ask first next time.
          {why === 'never' && ' Disable this automation entirely.'}
          <div style={{ marginTop: 6, fontSize: 11, color: KX2.ink3 }}>
            You can turn this back on anytime in <span style={{ color: KX2.brand, fontWeight: 600 }}>Settings → Trust &amp; autonomy</span>.
          </div>
        </div>

        <div style={{ display: 'flex', gap: 6, marginTop: 16 }}>
          <button onClick={onConfirm} style={{
            flex: 1, padding: '11px 12px', borderRadius: 12, background: KX2.brand,
            color: '#fff', border: 'none', fontWeight: 600, fontSize: 14, cursor: 'pointer',
          }}>Undo and remember</button>
          <button onClick={onClose} style={{
            padding: '11px 16px', borderRadius: 12, background: KX2.chipBg,
            color: KX2.ink, border: `1px solid ${KX2.glassLine}`, fontSize: 13, cursor: 'pointer',
          }}>Cancel</button>
        </div>
      </div>
    </KxV2Sheet>
  );
}

// ============ FLOATING UNDO BAR ============
function KxV2UndoBar({ visible, label, onUndo, onDismiss }) {
  const [secs, setSecs] = React.useState(8);
  React.useEffect(() => {
    if (!visible) return;
    setSecs(8);
    const t = setInterval(() => setSecs(s => s <= 1 ? (clearInterval(t), onDismiss?.(), 0) : s - 1), 1000);
    return () => clearInterval(t);
  }, [visible]);

  if (!visible) return null;
  return (
    <div style={{
      position: 'absolute', left: 12, right: 12, bottom: 78, zIndex: 25,
      ...kx2Glass({ borderRadius: 14 }),
      background: 'rgba(20, 14, 38, .92)',
      padding: '10px 12px', display: 'flex', alignItems: 'center', gap: 10,
      animation: 'kxv2SlideUp 220ms cubic-bezier(.2,.8,.2,1)',
      boxShadow: '0 12px 32px rgba(0,0,0,.5)',
    }}>
      <span style={{ width: 6, height: 6, borderRadius: 3, background: KX2.approve }} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13, color: KX2.ink, fontFamily: KX2.fontUI, lineHeight: 1.3 }}>{label}</div>
        <div style={{ fontSize: 10, color: KX2.ink3, marginTop: 1, fontFamily: KX2.fontMono }}>undo in {secs}s</div>
      </div>
      <button onClick={onUndo} style={{
        padding: '6px 12px', borderRadius: 8, background: KX2.chipBg,
        color: KX2.ink, border: `1px solid ${KX2.glassLine}`,
        fontFamily: KX2.fontUI, fontSize: 12, fontWeight: 600, cursor: 'pointer',
      }}>Undo</button>
    </div>
  );
}

// ============ SIMPLE SETTINGS SHEET ============
function KxV2SettingsSheet({ open, onClose, onOpenMemory, onOpenTrust, onOpenTeach }) {
  const rows = [
    { icon: '◈', label: 'Memory',     hint: 'What I know about you',         go: onOpenMemory },
    { icon: '◐', label: 'Trust & autonomy', hint: 'Adjust how much I do alone', go: onOpenTrust },
    { icon: '↗', label: 'Automations', hint: 'Recipes I follow on my own',    go: onOpenTeach },
    { icon: '◷', label: 'Quiet hours', hint: 'Don\'t ping me 7pm – 7am',       go: null },
    { icon: '◌', label: 'Notification style', hint: 'Push, banner, or silent', go: null },
    { icon: '◉', label: 'Connected accounts', hint: 'QuickBooks, Calendar, SMS', go: null },
    { icon: '⊘', label: 'Pause Kayser',  hint: 'Take a break from automations', go: null, danger: true },
  ];
  return (
    <KxV2Sheet open={open} onClose={onClose} title="Settings">
      <div style={{ padding: '12px 14px 22px', display: 'grid', gap: 6 }}>
        {rows.map(r => (
          <button key={r.label} onClick={r.go ? () => { onClose(); setTimeout(r.go, 200); } : null}
            disabled={!r.go}
            style={{
              ...kx2GlassThin({ borderRadius: 10 }),
              padding: '11px 12px', display: 'flex', alignItems: 'center', gap: 12,
              cursor: r.go ? 'pointer' : 'default', textAlign: 'left',
              color: r.danger ? KX2.reject : KX2.ink, fontFamily: KX2.fontUI,
              opacity: r.go ? 1 : 0.55,
            }}>
            <span style={{
              width: 28, height: 28, borderRadius: 8, background: KX2.chipBg,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontFamily: KX2.fontMono, color: r.danger ? KX2.reject : KX2.ink2, fontSize: 13,
            }}>{r.icon}</span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 14, fontWeight: 600 }}>{r.label}</div>
              <div style={{ fontSize: 11.5, color: KX2.ink3, marginTop: 1 }}>{r.hint}</div>
            </div>
            {r.go ? <span style={{ color: KX2.ink3, fontFamily: KX2.fontMono, fontSize: 12 }}>›</span>
                  : <span style={{ color: KX2.ink3, fontFamily: KX2.fontMono, fontSize: 9, letterSpacing: 0.4 }}>SOON</span>}
          </button>
        ))}
      </div>
    </KxV2Sheet>
  );
}

// ============ MAIN MENU DRAWER ============
// The real "Menu" — account, billing, settings, help.
// Distinct from Commands (the palette, which runs actions in the chat).
//
// `me` is the /api/v1/me response (or an empty object pre-fetch). When
// populated, the Account section's Profile + Email rows render from
// the real Google identity instead of the prototype's "Wes Kayser /
// wes@kayserrepair.com" mock. Phone isn't in /me yet, so the email-
// only hint stops at the address.
function KxV2MenuSheet({ open, onClose, onOpenMemory, onOpenTrust, onOpenTeach, onOpenConversations, me }) {
  const live = !!(me && me.email);
  const profileHint = live
    ? [me.name || me.email.split('@')[0], me.business].filter(Boolean).join(' · ')
    : 'Wes Kayser · Kayser Foundation Repair';
  const emailHint = live
    ? me.email
    : 'wes@kayserrepair.com · 817-555-0142';
  const sections = [
    {
      title: 'Account',
      rows: [
        { icon: '◉', label: 'Profile',           hint: profileHint, go: null },
        { icon: '✉', label: 'Email & phone',     hint: emailHint,   go: null },
        { icon: '$', label: 'Billing',           hint: 'Pro plan · $49/mo · renews May 12',     go: null },
      ],
    },
    {
      title: 'How I work',
      rows: [
        { icon: '◐', label: 'Trust & autonomy',  hint: 'Adjust how much I do alone', go: onOpenTrust },
        { icon: '◈', label: 'What I know about you', hint: 'Memory & profile', go: onOpenMemory },
        { icon: '↗', label: 'Automations',       hint: 'Routines you taught me',  go: onOpenTeach },
        { icon: '◉', label: 'Conversations',     hint: 'Browse by customer or job', go: onOpenConversations },
      ],
    },
    {
      title: 'Connected services',
      rows: [
        { icon: 'G', label: 'Gmail',             hint: 'Connected · synced 4m ago',  go: null },
        { icon: 'T', label: 'Twilio SMS',        hint: 'Connected · A2P approved',   go: null },
        { icon: 'Q', label: 'QuickBooks',        hint: 'Connected · synced 4m ago',  go: null },
        { icon: 'C', label: 'Google Calendar',   hint: 'Connected · synced 1h ago',  go: null },
        { icon: 'S', label: 'Stripe',            hint: 'Not connected',              go: null },
      ],
    },
    {
      title: 'Preferences',
      rows: [
        { icon: '◷', label: 'Quiet hours',           hint: "Don't ping me 7pm – 7am",  go: null },
        { icon: '◌', label: 'Notifications',        hint: 'Push, sound, banner style',  go: null },
        { icon: '⊘', label: 'Pause Kayser',         hint: 'Take a break from automations', go: null, danger: true },
      ],
    },
    {
      title: 'Support',
      rows: [
        { icon: '?', label: 'Help & guides',     hint: "How Kayser works",            go: null },
        { icon: '@', label: 'Talk to a human',   hint: 'Reach the Kayser team',       go: null },
        { icon: '↩', label: 'Sign out',          hint: null,                          go: null, danger: true },
      ],
    },
  ];

  return (
    <KxV2Sheet open={open} onClose={onClose} title="Menu">
      <div style={{ padding: '6px 14px 24px' }}>
        {sections.map((s, si) => (
          <div key={s.title} style={{ marginTop: si === 0 ? 6 : 18 }}>
            <div style={{
              fontFamily: KX2.fontMono, fontSize: 10, color: KX2.ink3,
              letterSpacing: 0.6, textTransform: 'uppercase',
              padding: '4px 4px 8px',
            }}>{s.title}</div>
            <div style={{ display: 'grid', gap: 4 }}>
              {s.rows.map(r => (
                <button key={r.label}
                  onClick={r.go ? () => { onClose(); setTimeout(r.go, 200); } : null}
                  disabled={!r.go}
                  style={{
                    ...kx2GlassThin({ borderRadius: 10 }),
                    padding: '10px 12px', display: 'flex', alignItems: 'center', gap: 12,
                    cursor: r.go ? 'pointer' : 'default', textAlign: 'left',
                    color: r.danger ? KX2.reject : KX2.ink, fontFamily: KX2.fontUI,
                    opacity: r.go || !r.go && r.hint ? 1 : 0.55,
                  }}>
                  <span style={{
                    width: 28, height: 28, borderRadius: 8, background: KX2.chipBg,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontFamily: KX2.fontMono, color: r.danger ? KX2.reject : KX2.ink2, fontSize: 13,
                  }}>{r.icon}</span>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 14, fontWeight: 600 }}>{r.label}</div>
                    {r.hint && <div style={{ fontSize: 11.5, color: KX2.ink3, marginTop: 1 }}>{r.hint}</div>}
                  </div>
                  {r.go
                    ? <span style={{ color: KX2.ink3, fontFamily: KX2.fontMono, fontSize: 12 }}>›</span>
                    : (r.hint && <span style={{ color: KX2.ink3, fontFamily: KX2.fontMono, fontSize: 9, letterSpacing: 0.4 }}>SOON</span>)
                  }
                </button>
              ))}
            </div>
          </div>
        ))}
      </div>
    </KxV2Sheet>
  );
}

Object.assign(window, {
  KxV2MemorySheet, KxV2ApprovalSheet, KxV2WrongSheet, KxV2UndoBar,
  KxV2SettingsSheet, KxV2MenuSheet, KXV2_USER_PROFILE, KXV2_AGENT_MEMORY,
});
