// Kayser v2 — Quick menu (avatar dropdown) + Settings page (full surface)
// Option C: separate "account stuff" from "how Kayser works."
//   QuickMenu = small dropdown anchored to the top-right ⋯
//   SettingsPage = full takeover (mobile full-screen, desktop right pane)

// Two-letter monogram from a display name. Handles single-word names
// ("Madonna" → "MA"), email-derived fallbacks ("isaiah" → "IS"), and
// missing names ("" → "·"). Used by the quick menu's avatar fallback
// when /me hasn't returned a picture URL yet.
function kxInitialsFromName(name) {
  if (!name) return '·';
  const cleaned = String(name).trim();
  if (!cleaned) return '·';
  const parts = cleaned.split(/\s+/).filter(Boolean);
  if (parts.length >= 2) {
    return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
  }
  // Single word — take the first two letters (handles "Isaiah" → "IS").
  return cleaned.slice(0, 2).toUpperCase();
}

// ============ QUICK MENU ============
// Small floating dropdown. Anchored to the ⋯ button. Closes on outside-click.
//
// `me` is the /api/v1/me response shape (or an empty object when the
// fetch hasn't landed). When non-empty we render the operator's real
// Google profile (name, business, picture); otherwise fall through to
// the prototype's mock copy so the standalone demo still looks
// presentable.
function KxV2QuickMenu({ open, onClose, anchorRef, me, onOpenSettings, onOpenBilling, onOpenHelp, onSignOut }) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!open) return;
    const onDoc = (e) => {
      if (ref.current && !ref.current.contains(e.target)) {
        onClose?.();
      }
    };
    // Use mouseup (after the button's onClick fires) so we don't immediately close
    document.addEventListener('mouseup', onDoc);
    return () => document.removeEventListener('mouseup', onDoc);
  }, [open, onClose]);

  if (!open) return null;
  const isDesktop = !!window.__kxDesktop;
  // Resolve identity. Empty `me` (no token, or /me still in flight)
  // gets the prototype defaults so the menu always looks intentional.
  const live = !!(me && me.email);
  const displayName = live ? (me.name || me.email.split('@')[0]) : 'Wes Kayser';
  const businessName = live ? (me.business || '') : 'Kayser Foundation Repair';
  const pictureUrl = live ? me.picture : null;
  const initials = kxInitialsFromName(displayName);
  return (
    <div ref={ref} style={{
      position: isDesktop ? 'fixed' : 'absolute',
      top: isDesktop ? 76 : 50,
      right: isDesktop ? 18 : 12,
      zIndex: 250,
      width: 264,
      ...kx2Glass({ borderRadius: 14 }),
      background: KX2.glassSheet,
      boxShadow: '0 12px 40px rgba(0,0,0,.45)',
      padding: 6, fontFamily: KX2.fontUI,
      animation: 'kxv2FadeIn 120ms ease-out',
    }}>
      {/* Profile header */}
      <div style={{
        padding: '12px 12px 10px',
        borderBottom: `1px solid ${KX2.glassLine}`,
        display: 'flex', alignItems: 'center', gap: 10,
      }}>
        {pictureUrl ? (
          // Real Google profile picture. `referrerPolicy=no-referrer` is
          // required — Google's CDN 403s requests carrying our origin.
          <img src={pictureUrl} alt="" referrerPolicy="no-referrer" style={{
            width: 36, height: 36, borderRadius: 18, objectFit: 'cover',
            flexShrink: 0,
          }} />
        ) : (
          <div style={{
            width: 36, height: 36, borderRadius: 18,
            background: `linear-gradient(135deg, ${KX2.brand} 0%, ${KX2.brandDeep} 100%)`,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: '#fff', fontFamily: KX2.fontBrand, fontWeight: 700, fontSize: 14,
            flexShrink: 0,
          }}>{initials}</div>
        )}
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{
            fontSize: 13.5, fontWeight: 600, color: KX2.ink,
            whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
          }}>{displayName}</div>
          <div style={{
            fontSize: 11, color: KX2.ink3, marginTop: 1,
            whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
          }}>{businessName}</div>
        </div>
        {/* PRO badge: only render in prototype mode. We don't have a
            real billing read yet, so showing it for every signed-in
            operator would be a lie. Comes back in the billing wire-up. */}
        {!live && (
          <span style={{
            fontFamily: KX2.fontMono, fontSize: 9.5, letterSpacing: 0.4,
            color: KX2.brand, background: KX2.brandSoft,
            padding: '3px 7px', borderRadius: 6, fontWeight: 700,
          }}>PRO</span>
        )}
      </div>

      <QuickMenuRow icon="◷" label="Settings" hint="How Kayser works" onClick={onOpenSettings} />
      <QuickMenuRow icon="$" label="Billing" hint="Pro · $49/mo · May 12" onClick={onOpenBilling} />
      <QuickMenuRow icon="?" label="Help" hint="Guides & support" onClick={onOpenHelp} />
      <div style={{ height: 1, background: KX2.glassLine, margin: '4px 0' }} />
      <QuickMenuRow icon="↩" label="Sign out" onClick={onSignOut} danger />
    </div>
  );
}

function QuickMenuRow({ icon, label, hint, onClick, danger }) {
  return (
    <button onClick={onClick} style={{
      display: 'flex', alignItems: 'center', gap: 10, width: '100%',
      padding: '8px 10px', borderRadius: 10, border: 'none', cursor: 'pointer',
      background: 'transparent',
      color: danger ? KX2.reject : KX2.ink, fontFamily: KX2.fontUI, textAlign: 'left',
    }}
      onMouseEnter={(e) => e.currentTarget.style.background = KX2.chipBg}
      onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
      <span style={{
        width: 24, height: 24, borderRadius: 6,
        background: KX2.chipBg, color: danger ? KX2.reject : KX2.ink2,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontFamily: KX2.fontMono, fontSize: 12,
      }}>{icon}</span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13.5, fontWeight: 500 }}>{label}</div>
        {hint && <div style={{ fontSize: 11, color: KX2.ink3, marginTop: 1 }}>{hint}</div>}
      </div>
    </button>
  );
}

// ============ SETTINGS PAGE ============
// Full settings surface. On desktop it takes over the right pane (renders inside it).
// On mobile it opens as a full-screen sheet (no rounded top — covers the whole app).
// Sections inside open their own sub-sheets (Trust, Memory, Conversations, Automations)
// so we reuse existing UIs.

const KXV2_SETTINGS_SECTIONS = [
  {
    title: 'How I work',
    rows: [
      { id: 'trust',         icon: '◐', label: 'Trust & autonomy',     hint: 'Adjust how much I do alone',          tag: null },
      { id: 'memory',        icon: '◈', label: 'What I know about you', hint: 'Memory & profile · 11 facts',         tag: null },
      { id: 'automations',   icon: '↗', label: 'Automations',           hint: 'Routines you taught me · 4',          tag: null },
      { id: 'conversations', icon: '◉', label: 'Conversations',         hint: 'Browse by customer or job',           tag: null },
    ],
  },
  {
    title: 'Connections',
    rows: [
      { id: 'gmail',         icon: 'G', label: 'Gmail',          hint: 'wes@kayserrepair.com · synced 4m ago', tag: 'OK' },
      { id: 'twilio',        icon: 'T', label: 'Twilio SMS',     hint: '+1 817 555 0142 · A2P approved',       tag: 'OK' },
      { id: 'quickbooks',    icon: 'Q', label: 'QuickBooks',     hint: 'Synced 4m ago',                          tag: 'OK' },
      { id: 'calendar',      icon: 'C', label: 'Google Calendar', hint: 'Synced 1h ago',                         tag: 'OK' },
      { id: 'stripe',        icon: 'S', label: 'Stripe',         hint: 'Connect to track payments',              tag: 'CONNECT' },
    ],
  },
  {
    title: 'Notifications',
    rows: [
      { id: 'push',          icon: '◌', label: 'Push notifications',    hint: 'On — banners + sound',                tag: null },
      { id: 'quiet',         icon: '◷', label: 'Quiet hours',           hint: "Don't ping me 7pm – 7am",             tag: null },
      { id: 'priority',      icon: '▲', label: 'What to interrupt me for', hint: 'Anything over $5K or new leads',   tag: null },
    ],
  },
  {
    title: 'Account',
    rows: [
      { id: 'profile',       icon: '◉', label: 'Profile',         hint: 'Wes Kayser · Kayser Foundation Repair', tag: null },
      { id: 'industry',      icon: '◆', label: 'Industry',        hint: 'Foundation repair (affects vocab)',     tag: null },
      { id: 'team',          icon: '◑', label: 'Team',            hint: '5 people · 2 leads',                    tag: null },
      { id: 'billing',       icon: '$', label: 'Billing',         hint: 'Pro · $49/mo · renews May 12',          tag: null },
    ],
  },
  {
    title: 'Danger zone',
    rows: [
      { id: 'pause',         icon: '⊘', label: 'Pause Kayser',    hint: 'Take a break from automations',         tag: null, danger: true },
      { id: 'reset',         icon: '↺', label: 'Reset memory',    hint: 'Forget what I know about you',          tag: null, danger: true },
      { id: 'delete',        icon: '✕', label: 'Delete account',  hint: null,                                     tag: null, danger: true },
    ],
  },
];

function KxV2SettingsPage({ open, onClose, onOpen, me }) {
  const [section, setSection] = React.useState('how-i-work');
  if (!open) return null;
  const isDesktop = !!window.__kxDesktop;
  // Per-row hint overrides driven by /me. Without these, the
  // "Profile" row reads "Wes Kayser · Kayser Foundation Repair" for
  // every operator. Other rows (industry, team, billing, memory count,
  // automation count, connections sync state) need their own backends
  // before we can replace their hardcoded hints — flagged for the next
  // truthfulness pass.
  const live = !!(me && me.email);
  const displayName = live ? (me.name || me.email.split('@')[0]) : null;
  const businessName = live ? me.business : null;
  const dynamicHints = live ? {
    profile: [displayName, businessName].filter(Boolean).join(' · '),
  } : {};

  const body = (
    <div style={{
      width: '100%', height: '100%',
      display: 'flex', flexDirection: 'column',
      background: KX2.glassSheet,
      backdropFilter: 'blur(28px) saturate(140%)',
      WebkitBackdropFilter: 'blur(28px) saturate(140%)',
      color: KX2.ink, fontFamily: KX2.fontUI, overflow: 'hidden',
    }}>
      {/* Header */}
      <div style={{
        padding: '14px 18px 12px',
        borderBottom: `1px solid ${KX2.glassLine}`,
        display: 'flex', alignItems: 'center', gap: 10, flexShrink: 0,
      }}>
        <button onClick={onClose} aria-label="Close settings" style={{
          width: 32, height: 32, borderRadius: 16, border: 'none',
          background: KX2.chipBg, color: KX2.ink2, cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
            <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
          </svg>
        </button>
        <div style={{
          fontFamily: KX2.fontBrand, fontSize: 18, fontWeight: 600,
          color: KX2.ink, letterSpacing: -0.3,
        }}>Settings</div>
      </div>

      {/* Body — list of sections w/ rows */}
      <div style={{ flex: 1, overflowY: 'auto', padding: '14px 18px 24px' }}>
        {KXV2_SETTINGS_SECTIONS.map((s, si) => (
          <div key={s.title} style={{ marginTop: si === 0 ? 0 : 22 }}>
            <div style={{
              fontFamily: KX2.fontMono, fontSize: 10, color: KX2.ink3,
              letterSpacing: 0.6, textTransform: 'uppercase', marginBottom: 8,
            }}>{s.title}</div>
            <div style={{ display: 'grid', gap: 4 }}>
              {s.rows.map(r => (
                <SettingsRow
                  key={r.id}
                  row={dynamicHints[r.id] ? { ...r, hint: dynamicHints[r.id] } : r}
                  onClick={() => onOpen?.(r.id)} />
              ))}
            </div>
          </div>
        ))}

        <div style={{
          marginTop: 28, padding: '14px 16px',
          ...kx2GlassThin({ borderRadius: 12 }),
          fontSize: 12, color: KX2.ink3, lineHeight: 1.5,
        }}>
          <div style={{ color: KX2.ink2, fontWeight: 500, marginBottom: 4 }}>Kayser · v2.4 · Pro plan</div>
          Your data lives on your dedicated VPS. Nothing here is used to train other models.
        </div>
      </div>
    </div>
  );

  if (isDesktop) {
    // Right-side drawer on desktop
    return (
      <div onClick={onClose} style={{
        position: 'fixed', inset: 0, zIndex: 200,
        background: 'rgba(0,0,0,.35)', backdropFilter: 'blur(2px)',
        display: 'flex', justifyContent: 'flex-end',
        animation: 'kxv2FadeIn 160ms ease-out',
      }}>
        <div onClick={(e) => e.stopPropagation()} style={{
          width: 'min(560px, 60vw)', height: '100%',
          borderLeft: `1px solid ${KX2.glassLine}`,
          animation: 'kxv2SlideInRight 220ms cubic-bezier(.2,.8,.2,1)',
        }}>{body}</div>
      </div>
    );
  }
  // Mobile / tablet: full-screen overlay
  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 60,
      animation: 'kxv2FadeIn 160ms ease-out',
    }}>
      {body}
    </div>
  );
}

function SettingsRow({ row, onClick }) {
  return (
    <button onClick={onClick} disabled={!onClick} style={{
      ...kx2GlassThin({ borderRadius: 10 }),
      padding: '11px 12px', display: 'flex', alignItems: 'center', gap: 12,
      cursor: 'pointer', textAlign: 'left', width: '100%',
      color: row.danger ? KX2.reject : KX2.ink, fontFamily: KX2.fontUI,
    }}
      onMouseEnter={(e) => e.currentTarget.style.background = KX2.chipBg}
      onMouseLeave={(e) => e.currentTarget.style.background = KX2.glassInput}>
      <span style={{
        width: 28, height: 28, borderRadius: 8,
        background: KX2.chipBg,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontFamily: KX2.fontMono, color: row.danger ? KX2.reject : KX2.ink2, fontSize: 13,
      }}>{row.icon}</span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 14, fontWeight: 600 }}>{row.label}</div>
        {row.hint && <div style={{ fontSize: 11.5, color: KX2.ink3, marginTop: 1 }}>{row.hint}</div>}
      </div>
      {row.tag === 'OK' && (
        <span style={{
          fontFamily: KX2.fontMono, fontSize: 9.5, letterSpacing: 0.4,
          color: KX2.approve, padding: '2px 6px', borderRadius: 4,
          background: 'rgba(52,211,153,.10)', fontWeight: 700,
        }}>OK</span>
      )}
      {row.tag === 'CONNECT' && (
        <span style={{
          fontFamily: KX2.fontMono, fontSize: 9.5, letterSpacing: 0.4,
          color: KX2.brand, padding: '2px 6px', borderRadius: 4,
          background: KX2.brandSoft, fontWeight: 700,
        }}>CONNECT</span>
      )}
      <span style={{ color: KX2.ink3, fontFamily: KX2.fontMono, fontSize: 12 }}>›</span>
    </button>
  );
}

Object.assign(window, {
  KxV2QuickMenu, KxV2SettingsPage, KXV2_SETTINGS_SECTIONS,
  KxV2BillingSheet, KxV2PauseSheet, KxV2ServiceSheet,
});

// ============ BILLING SHEET ============
function KxV2BillingSheet({ open, onClose }) {
  return (
    <KxV2Sheet open={open} onClose={onClose} title="Billing">
      <div style={{ padding: '14px 18px 28px' }}>
        {/* Current plan */}
        <div style={{ ...kx2Glass({ borderRadius: 14 }), padding: 16, marginBottom: 16 }}>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 6 }}>
            <span style={{ fontFamily: KX2.fontBrand, fontSize: 22, fontWeight: 700, color: KX2.ink, letterSpacing: -0.3 }}>Kayser Pro</span>
            <span style={{
              fontFamily: KX2.fontMono, fontSize: 9.5, letterSpacing: 0.4,
              color: KX2.brand, padding: '2px 7px', borderRadius: 4,
              background: KX2.brandSoft, fontWeight: 700,
            }}>ACTIVE</span>
          </div>
          <div style={{ fontSize: 13, color: KX2.ink2, lineHeight: 1.5 }}>$49/month · billed monthly</div>
          <div style={{ fontSize: 12, color: KX2.ink3, marginTop: 4 }}>Next charge May 12 · Visa ending 4242</div>
        </div>

        {/* This month usage */}
        <div style={{
          fontFamily: KX2.fontMono, fontSize: 10, letterSpacing: 0.6,
          color: KX2.ink3, textTransform: 'uppercase', marginBottom: 8,
        }}>This month</div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginBottom: 18 }}>
          {[
            { k: 'Actions handled', v: '124', sub: 'unlimited on Pro' },
            { k: 'AI tokens',       v: '~1.2M', sub: 'unlimited on Pro' },
            { k: 'Connected services', v: '4', sub: 'unlimited on Pro' },
            { k: 'Storage',         v: '2.1 GB', sub: 'of 50 GB' },
          ].map(s => (
            <div key={s.k} style={{ ...kx2GlassThin({ borderRadius: 10 }), padding: '10px 12px' }}>
              <div style={{ fontSize: 10.5, color: KX2.ink3, fontFamily: KX2.fontMono, letterSpacing: 0.3 }}>{s.k.toUpperCase()}</div>
              <div style={{ fontFamily: KX2.fontBrand, fontSize: 20, fontWeight: 700, color: KX2.ink, marginTop: 2 }}>{s.v}</div>
              <div style={{ fontSize: 11, color: KX2.ink3, marginTop: 2 }}>{s.sub}</div>
            </div>
          ))}
        </div>

        {/* Actions */}
        <div style={{ display: 'grid', gap: 8 }}>
          <button style={{
            ...kx2GlassThin({ borderRadius: 10 }),
            padding: '12px 14px', display: 'flex', alignItems: 'center', gap: 10,
            cursor: 'pointer', textAlign: 'left', color: KX2.ink, fontFamily: KX2.fontUI,
            border: `1px solid ${KX2.glassLine}`,
          }}>
            <span style={{
              width: 28, height: 28, borderRadius: 8, background: KX2.chipBg, color: KX2.ink2,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontFamily: KX2.fontMono, fontSize: 13,
            }}>$</span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 14, fontWeight: 500 }}>Manage payment method</div>
              <div style={{ fontSize: 11.5, color: KX2.ink3 }}>Update card, view receipts, change billing email</div>
            </div>
            <span style={{ color: KX2.ink3, fontFamily: KX2.fontMono, fontSize: 11 }}>↗</span>
          </button>
          <button style={{
            ...kx2GlassThin({ borderRadius: 10 }),
            padding: '12px 14px', display: 'flex', alignItems: 'center', gap: 10,
            cursor: 'pointer', textAlign: 'left', color: KX2.ink, fontFamily: KX2.fontUI,
            border: `1px solid ${KX2.glassLine}`,
          }}>
            <span style={{
              width: 28, height: 28, borderRadius: 8, background: KX2.chipBg, color: KX2.ink2,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontFamily: KX2.fontMono, fontSize: 13,
            }}>◷</span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 14, fontWeight: 500 }}>Switch plan</div>
              <div style={{ fontSize: 11.5, color: KX2.ink3 }}>Starter $19 · Pro $49 · Team $149/mo</div>
            </div>
            <span style={{ color: KX2.ink3, fontFamily: KX2.fontMono, fontSize: 11 }}>›</span>
          </button>
          <button style={{
            padding: '12px 14px', display: 'flex', alignItems: 'center', gap: 10,
            cursor: 'pointer', textAlign: 'left', color: KX2.reject, fontFamily: KX2.fontUI,
            background: 'transparent', border: `1px solid ${KX2.glassLine}`, borderRadius: 10,
          }}>
            <span style={{
              width: 28, height: 28, borderRadius: 8, background: KX2.chipBg, color: KX2.reject,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontFamily: KX2.fontMono, fontSize: 13,
            }}>⊘</span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 14, fontWeight: 500 }}>Cancel subscription</div>
              <div style={{ fontSize: 11.5, color: KX2.ink3 }}>You'll keep Pro until May 12</div>
            </div>
          </button>
        </div>

        <div style={{ fontSize: 11.5, color: KX2.ink3, marginTop: 18, lineHeight: 1.5, textAlign: 'center' }}>
          Billing handled by Stripe · receipts emailed to your Google account
        </div>
      </div>
    </KxV2Sheet>
  );
}

// ============ PAUSE SHEET ============
function KxV2PauseSheet({ open, onClose, paused, onTogglePause }) {
  return (
    <KxV2Sheet open={open} onClose={onClose} title={paused ? 'Resume Kayser' : 'Pause Kayser'}>
      <div style={{ padding: '20px 20px 28px', textAlign: 'center' }}>
        <div style={{
          width: 64, height: 64, borderRadius: 32, margin: '0 auto 18px',
          background: paused ? 'rgba(52,211,153,.15)' : 'rgba(251,191,36,.15)',
          color: paused ? KX2.approve : KX2.warn,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 28, fontFamily: KX2.fontMono, fontWeight: 700,
        }}>{paused ? '▶' : '⏸'}</div>
        <div style={{ fontFamily: KX2.fontBrand, fontSize: 20, fontWeight: 700, color: KX2.ink, letterSpacing: -0.3, marginBottom: 10 }}>
          {paused ? 'Pick up where I left off?' : 'Take a break from automations?'}
        </div>
        <div style={{ fontSize: 14, color: KX2.ink2, lineHeight: 1.5, maxWidth: 380, margin: '0 auto 20px' }}>
          {paused
            ? "I'll resume watching email, calendar, and texts. Any backlog from while I was paused will surface as a recap."
            : "I'll stop watching for things and stop sending. You can still chat with me. Turn me back on anytime."}
        </div>

        <div style={{
          ...kx2GlassThin({ borderRadius: 10 }),
          padding: '10px 14px', marginBottom: 20, textAlign: 'left',
          fontSize: 12, color: KX2.ink2, lineHeight: 1.5,
        }}>
          <span style={{ color: paused ? KX2.approve : KX2.warn, fontWeight: 600 }}>
            {paused ? 'When I resume:' : 'While paused:'}
          </span>{' '}
          {paused
            ? "I'll show you everything that happened, ask before catching up, and start fresh."
            : "No auto-handled actions. No proactive pings. No scheduled sends. Already-sent stuff stays sent."}
        </div>

        <button onClick={() => onTogglePause(!paused)} style={{
          width: '100%', padding: '13px', borderRadius: 12, border: 'none',
          background: paused ? KX2.brand : KX2.warn,
          color: paused ? '#fff' : '#3b2300',
          fontFamily: KX2.fontUI, fontSize: 14, fontWeight: 600, cursor: 'pointer',
          boxShadow: paused ? '0 6px 18px rgba(124,58,237,.4)' : 'none',
        }}>{paused ? "Pick up where you left off" : "Pause for now"}</button>
        <button onClick={onClose} style={{
          marginTop: 8, width: '100%', padding: '11px',
          background: 'transparent', color: KX2.ink2, border: 'none',
          fontFamily: KX2.fontUI, fontSize: 13, cursor: 'pointer',
        }}>Cancel</button>
      </div>
    </KxV2Sheet>
  );
}

// ============ CONNECTED SERVICE DETAIL SHEET ============
const KXV2_SERVICE_DETAILS = {
  gmail: {
    name: 'Gmail',
    account: 'wes@kayserrepair.com',
    status: 'Connected',
    syncing: 'Last synced 4m ago',
    permissions: ['Read inbound messages', 'Draft and send replies (on approval)', 'Apply labels to organize'],
  },
  twilio: {
    name: 'Twilio SMS',
    account: '+1 817 555 0142',
    status: 'Connected · A2P approved',
    syncing: 'Last message 14m ago',
    permissions: ['Receive inbound texts', 'Send texts (on approval)', 'Track delivery and reads'],
  },
  quickbooks: {
    name: 'QuickBooks',
    account: 'Kayser Foundation Repair, LLC',
    status: 'Connected',
    syncing: 'Last synced 4m ago',
    permissions: ['Read invoices, bills, customers', 'Create draft invoices (on approval)', 'Log expenses to jobs'],
  },
  calendar: {
    name: 'Google Calendar',
    account: 'wes@kayserrepair.com · Primary',
    status: 'Connected',
    syncing: 'Last synced 1h ago',
    permissions: ['Read events and busy times', 'Create and reschedule events (on approval)', 'Send invitations'],
  },
  stripe: {
    name: 'Stripe',
    account: null,
    status: 'Not connected',
    syncing: null,
    permissions: ['Read payments, payouts, fees', 'Reconcile payments to invoices'],
  },
};

function KxV2ServiceSheet({ open, service, onClose }) {
  const d = service ? KXV2_SERVICE_DETAILS[service] : null;
  if (!d) return null;
  const connected = d.status !== 'Not connected';
  return (
    <KxV2Sheet open={open} onClose={onClose} title={d.name}>
      <div style={{ padding: '14px 18px 24px' }}>
        <div style={{ ...kx2Glass({ borderRadius: 14 }), padding: 16, marginBottom: 16 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
            <span style={{ width: 8, height: 8, borderRadius: 4,
              background: connected ? KX2.approve : KX2.ink3 }} />
            <span style={{ fontFamily: KX2.fontMono, fontSize: 11, color: connected ? KX2.approve : KX2.ink3,
              fontWeight: 700, letterSpacing: 0.4, textTransform: 'uppercase' }}>{d.status}</span>
          </div>
          {d.account && <div style={{ fontSize: 14, color: KX2.ink, fontWeight: 500 }}>{d.account}</div>}
          {d.syncing && <div style={{ fontSize: 11.5, color: KX2.ink3, marginTop: 2 }}>{d.syncing}</div>}
        </div>

        <div style={{
          fontFamily: KX2.fontMono, fontSize: 10, letterSpacing: 0.6,
          color: KX2.ink3, textTransform: 'uppercase', marginBottom: 8,
        }}>What I can do</div>
        <div style={{ ...kx2GlassThin({ borderRadius: 10 }), padding: '12px 14px', marginBottom: 18 }}>
          {d.permissions.map((p, i) => (
            <div key={i} style={{ display: 'flex', gap: 10, marginBottom: i < d.permissions.length - 1 ? 8 : 0 }}>
              <span style={{ color: connected ? KX2.approve : KX2.ink3, fontSize: 13, flexShrink: 0 }}>✓</span>
              <span style={{ fontSize: 13, color: KX2.ink2, lineHeight: 1.5 }}>{p}</span>
            </div>
          ))}
        </div>

        {connected ? (
          <div style={{ display: 'grid', gap: 8 }}>
            <button style={{
              ...kx2GlassThin({ borderRadius: 10 }), padding: '12px 14px',
              display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer',
              textAlign: 'left', color: KX2.ink, fontFamily: KX2.fontUI,
              border: `1px solid ${KX2.glassLine}`,
            }}>
              <span style={{ width: 24, height: 24, borderRadius: 6, background: KX2.chipBg,
                color: KX2.ink2, fontFamily: KX2.fontMono, fontSize: 12, fontWeight: 700,
                display: 'flex', alignItems: 'center', justifyContent: 'center' }}>↻</span>
              <span style={{ flex: 1, fontSize: 13.5 }}>Sync now</span>
            </button>
            <button onClick={onClose} style={{
              padding: '12px 14px', cursor: 'pointer', textAlign: 'left',
              color: KX2.reject, fontFamily: KX2.fontUI,
              background: 'transparent', border: `1px solid ${KX2.glassLine}`, borderRadius: 10,
              display: 'flex', alignItems: 'center', gap: 10,
            }}>
              <span style={{ width: 24, height: 24, borderRadius: 6, background: KX2.chipBg,
                color: KX2.reject, fontFamily: KX2.fontMono, fontSize: 12, fontWeight: 700,
                display: 'flex', alignItems: 'center', justifyContent: 'center' }}>✕</span>
              <span style={{ flex: 1, fontSize: 13.5 }}>Disconnect {d.name}</span>
            </button>
          </div>
        ) : (
          <button style={{
            width: '100%', padding: '13px', borderRadius: 12, border: 'none',
            background: KX2.brand, color: '#fff',
            fontFamily: KX2.fontUI, fontSize: 14, fontWeight: 600, cursor: 'pointer',
            boxShadow: '0 6px 18px rgba(124,58,237,.4)',
          }}>Connect {d.name}</button>
        )}
      </div>
    </KxV2Sheet>
  );
}
