// Kayser v2 — Teach Kayser an automation sheet + Level-up celebration.

// ============ TEACH SHEET ============
// Three-step linear flow: trigger → action → confidence threshold.
// Designed to feel like a Raycast snippet/hotkey: tight, technical, but legible.

const KXV2_TRIGGER_SUGGESTIONS = [
  { icon: '◷', label: 'Invoice goes 7+ days overdue',          tag: 'invoice.overdue' },
  { icon: '◷', label: 'New lead arrives via website',           tag: 'lead.new' },
  { icon: '◷', label: 'Quote unanswered for 3 days',            tag: 'quote.cold' },
  { icon: '◷', label: '70%+ rain forecast on a job day',        tag: 'weather.rain' },
  { icon: '◷', label: 'Customer texts after hours',             tag: 'sms.afterhours' },
];

const KXV2_ACTION_SUGGESTIONS = [
  { icon: '↗', label: 'Send a reminder text',                   tag: 'send.sms' },
  { icon: '↗', label: 'Reschedule the job',                     tag: 'job.reschedule' },
  { icon: '↗', label: 'Reply with availability + book a call',  tag: 'lead.respond' },
  { icon: '↗', label: 'Notify me only',                         tag: 'notify' },
  { icon: '↗', label: 'Draft for my approval',                  tag: 'draft' },
];

function KxV2TeachSheet({ open, onClose }) {
  const [step, setStep]   = React.useState(0);
  const [trig, setTrig]   = React.useState(null);
  const [act,  setAct]    = React.useState(null);
  const [conf, setConf]   = React.useState(70);

  React.useEffect(() => {
    if (open) { setStep(0); setTrig(null); setAct(null); setConf(70); }
  }, [open]);

  const stepDot = (i, active) => (
    <div key={i} style={{
      width: active ? 16 : 6, height: 6, borderRadius: 3,
      background: active ? KX2.brand : 'rgba(255,255,255,.18)',
      transition: 'all 200ms',
    }} />
  );

  return (
    <KxV2Sheet open={open} onClose={onClose} title="Teach an automation">
      <div style={{ padding: '14px 16px 24px' }}>

        {/* Step indicator */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 4, justifyContent: 'center', marginBottom: 18 }}>
          {[0, 1, 2].map(i => stepDot(i, i === step))}
        </div>

        {/* STEP 0 — TRIGGER */}
        {step === 0 && (
          <div>
            <div style={{ fontFamily: KX2.fontMono, fontSize: 10, letterSpacing: 0.6, color: KX2.ink3, textTransform: 'uppercase' }}>WHEN</div>
            <div style={{ fontFamily: KX2.fontBrand, fontSize: 22, fontWeight: 600, color: KX2.ink, marginTop: 4, letterSpacing: -0.4 }}>
              What should I watch for?
            </div>
            <div style={{ fontSize: 13, color: KX2.ink2, marginTop: 6, lineHeight: 1.4 }}>
              Pick a signal — or type your own.
            </div>

            <div style={{ marginTop: 14, display: 'grid', gap: 6 }}>
              {KXV2_TRIGGER_SUGGESTIONS.map(s => (
                <button key={s.tag} onClick={() => setTrig(s)} style={{
                  ...kx2GlassThin({ borderRadius: 10 }),
                  padding: '10px 12px', display: 'flex', alignItems: 'center', gap: 10,
                  cursor: 'pointer', textAlign: 'left',
                  border: trig?.tag === s.tag ? `1px solid ${KX2.brand}` : `1px solid ${KX2.glassLine}`,
                  color: KX2.ink, fontFamily: KX2.fontUI, fontSize: 13.5,
                }}>
                  <span style={{ fontFamily: KX2.fontMono, color: KX2.ink2, width: 14 }}>{s.icon}</span>
                  <span style={{ flex: 1 }}>{s.label}</span>
                  {trig?.tag === s.tag && <span style={{ color: KX2.brand, fontSize: 14 }}>✓</span>}
                </button>
              ))}
            </div>

            <div style={{ marginTop: 10 }}>
              <div style={{
                ...kx2GlassThin({ borderRadius: 10 }),
                padding: '10px 12px', display: 'flex', alignItems: 'center', gap: 10,
              }}>
                <span style={{ fontFamily: KX2.fontMono, color: KX2.ink3, fontSize: 14 }}>+</span>
                <input placeholder="Or describe it…"
                  style={{ flex: 1, background: 'transparent', border: 'none', outline: 'none',
                    color: KX2.ink, fontSize: 13.5, fontFamily: KX2.fontUI }} />
              </div>
            </div>
          </div>
        )}

        {/* STEP 1 — ACTION */}
        {step === 1 && (
          <div>
            <div style={{ fontFamily: KX2.fontMono, fontSize: 10, letterSpacing: 0.6, color: KX2.ink3, textTransform: 'uppercase' }}>THEN</div>
            <div style={{ fontFamily: KX2.fontBrand, fontSize: 22, fontWeight: 600, color: KX2.ink, marginTop: 4, letterSpacing: -0.4 }}>
              What should I do?
            </div>
            <div style={{ fontSize: 13, color: KX2.ink2, marginTop: 6, lineHeight: 1.4 }}>
              Triggered by: <span style={{ color: KX2.ink, fontWeight: 600 }}>{trig?.label || '—'}</span>
            </div>

            <div style={{ marginTop: 14, display: 'grid', gap: 6 }}>
              {KXV2_ACTION_SUGGESTIONS.map(s => (
                <button key={s.tag} onClick={() => setAct(s)} style={{
                  ...kx2GlassThin({ borderRadius: 10 }),
                  padding: '10px 12px', display: 'flex', alignItems: 'center', gap: 10,
                  cursor: 'pointer', textAlign: 'left',
                  border: act?.tag === s.tag ? `1px solid ${KX2.brand}` : `1px solid ${KX2.glassLine}`,
                  color: KX2.ink, fontFamily: KX2.fontUI, fontSize: 13.5,
                }}>
                  <span style={{ fontFamily: KX2.fontMono, color: KX2.ink2, width: 14 }}>{s.icon}</span>
                  <span style={{ flex: 1 }}>{s.label}</span>
                  {act?.tag === s.tag && <span style={{ color: KX2.brand, fontSize: 14 }}>✓</span>}
                </button>
              ))}
            </div>
          </div>
        )}

        {/* STEP 2 — CONFIDENCE */}
        {step === 2 && (
          <div>
            <div style={{ fontFamily: KX2.fontMono, fontSize: 10, letterSpacing: 0.6, color: KX2.ink3, textTransform: 'uppercase' }}>HOW FAR</div>
            <div style={{ fontFamily: KX2.fontBrand, fontSize: 22, fontWeight: 600, color: KX2.ink, marginTop: 4, letterSpacing: -0.4 }}>
              How much rope?
            </div>
            <div style={{ fontSize: 13, color: KX2.ink2, marginTop: 6, lineHeight: 1.4 }}>
              I'll start by drafting and asking. As you keep approving, I'll do it on my own.
            </div>

            {/* Live recipe preview */}
            <div style={{
              ...kx2Glass({ borderRadius: 12 }),
              padding: 12, marginTop: 14,
            }}>
              <div style={{ fontFamily: KX2.fontMono, fontSize: 10, color: KX2.ink3, letterSpacing: 0.4 }}>RECIPE</div>
              <div style={{ marginTop: 8, fontFamily: KX2.fontUI, fontSize: 13.5, color: KX2.ink, lineHeight: 1.5 }}>
                <span style={{ color: KX2.ink3 }}>When </span>
                <span style={{ color: KX2.warn, fontWeight: 600 }}>{trig?.label.toLowerCase() || '…'}</span>
                <br />
                <span style={{ color: KX2.ink3 }}>then </span>
                <span style={{ color: KX2.brand, fontWeight: 600 }}>{act?.label.toLowerCase() || '…'}</span>
              </div>
            </div>

            {/* Confidence slider */}
            <div style={{ marginTop: 18 }}>
              <div style={{ display: 'flex', alignItems: 'baseline', marginBottom: 8 }}>
                <div style={{ fontSize: 12, color: KX2.ink2, fontFamily: KX2.fontUI }}>Auto-handle threshold</div>
                <span style={{ flex: 1 }} />
                <div style={{ fontFamily: KX2.fontMono, fontSize: 13, color: KX2.brand, fontWeight: 700, fontVariantNumeric: 'tabular-nums' }}>{conf}%</div>
              </div>
              <input type="range" min="0" max="100" value={conf} onChange={(e) => setConf(+e.target.value)}
                style={{ width: '100%', accentColor: KX2.brand }} />
              <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 6, fontFamily: KX2.fontMono, fontSize: 10, color: KX2.ink3 }}>
                <span>Always ask</span>
                <span>Just do it</span>
              </div>
            </div>

            <div style={{
              ...kx2GlassThin({ borderRadius: 10 }),
              marginTop: 14, padding: '10px 12px',
              fontSize: 12, color: KX2.ink2, lineHeight: 1.45,
            }}>
              <span style={{ color: KX2.brand, fontWeight: 600 }}>At {conf}%: </span>
              {conf < 30 && "I'll always ask before doing this. You stay in full control."}
              {conf >= 30 && conf < 70 && "I'll draft + ask the first 5 times. After 3 in a row of 'send as-is', I'll start handling it."}
              {conf >= 70 && conf < 95 && "I'll handle it on my own and tell you after. You can undo within 5 minutes."}
              {conf >= 95 && "I'll handle it silently. You'll see it in the daily summary."}
            </div>
          </div>
        )}

        {/* Footer nav */}
        <div style={{ display: 'flex', gap: 8, marginTop: 22 }}>
          {step > 0 && (
            <button onClick={() => setStep(step - 1)} style={{
              padding: '11px 16px', borderRadius: 12,
              background: KX2.chipBg, border: `1px solid ${KX2.glassLine}`,
              color: KX2.ink, fontSize: 14, fontWeight: 600, fontFamily: KX2.fontUI,
              cursor: 'pointer',
            }}>Back</button>
          )}
          <span style={{ flex: 1 }} />
          {step < 2 ? (
            <button onClick={() => setStep(step + 1)}
              disabled={(step === 0 && !trig) || (step === 1 && !act)}
              style={{
                padding: '11px 18px', borderRadius: 12, border: 'none',
                background: ((step === 0 && trig) || (step === 1 && act)) ? KX2.brand : KX2.chipBg,
                color: '#fff', fontSize: 14, fontWeight: 600, fontFamily: KX2.fontUI,
                cursor: 'pointer', opacity: ((step === 0 && trig) || (step === 1 && act)) ? 1 : 0.5,
                boxShadow: ((step === 0 && trig) || (step === 1 && act)) ? '0 6px 18px rgba(124,58,237,.4)' : 'none',
              }}>Next →</button>
          ) : (
            <button onClick={onClose} style={{
              padding: '11px 18px', borderRadius: 12, border: 'none',
              background: KX2.brand, color: '#fff', fontSize: 14, fontWeight: 600,
              fontFamily: KX2.fontUI, cursor: 'pointer',
              boxShadow: '0 6px 18px rgba(124,58,237,.4)',
            }}>Save automation</button>
          )}
        </div>
      </div>
    </KxV2Sheet>
  );
}

// ============ LEVEL-UP CELEBRATION ============
// One-time inline message in chat. Quiet but with a subtle animated ring.

function KxV2LevelUp({ tier, onDismiss, onSeeMore }) {
  if (!tier) return null;
  return (
    <div style={{ padding: '8px 14px' }}>
      <div style={{
        ...kx2Glass({ borderRadius: 16 }),
        padding: 14, position: 'relative', overflow: 'hidden',
        background: `linear-gradient(135deg, ${KX2.brandSoft} 0%, rgba(20,14,38,.55) 100%)`,
        border: `1px solid ${KX2.brand}`,
        boxShadow: '0 8px 30px rgba(124,58,237,.25)',
      }}>
        {/* Animated ring/shimmer */}
        <div style={{
          position: 'absolute', top: -40, right: -40, width: 140, height: 140,
          borderRadius: 70,
          background: `radial-gradient(circle, ${KX2.brand} 0%, transparent 70%)`,
          opacity: 0.35,
          animation: 'kxv2Pulse 3s ease-in-out infinite',
        }} />

        <div style={{ display: 'flex', alignItems: 'center', gap: 10, position: 'relative' }}>
          <div style={{
            width: 36, height: 36, borderRadius: 18,
            background: KX2.brand, color: '#fff',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontFamily: KX2.fontMono, fontWeight: 700, fontSize: 13,
            boxShadow: '0 0 0 4px rgba(124,58,237,.2)',
          }}>L{tier.lvl}</div>
          <div style={{ flex: 1 }}>
            <div style={{
              fontFamily: KX2.fontMono, fontSize: 10, color: KX2.brand,
              letterSpacing: 0.8, fontWeight: 700,
            }}>LEVELED UP</div>
            <div style={{
              fontFamily: KX2.fontBrand, fontSize: 17, fontWeight: 700, color: KX2.ink,
              letterSpacing: -0.3, marginTop: 2,
            }}>Kayser is now an {tier.name}</div>
          </div>
        </div>
        <div style={{
          fontSize: 13, color: KX2.ink2, marginTop: 10, lineHeight: 1.45,
          position: 'relative',
        }}>{tier.blurb}</div>

        <div style={{ display: 'flex', gap: 6, marginTop: 12, position: 'relative' }}>
          <button onClick={onSeeMore} style={{
            flex: 1, padding: '8px 10px', borderRadius: 10, fontSize: 12.5, fontWeight: 600,
            fontFamily: KX2.fontUI, cursor: 'pointer',
            background: KX2.brand, color: '#fff', border: 'none',
          }}>See what's new</button>
          <button onClick={onDismiss} style={{
            padding: '8px 12px', borderRadius: 10, fontSize: 12.5, fontWeight: 600,
            fontFamily: KX2.fontUI, cursor: 'pointer',
            background: KX2.chipBg, color: KX2.ink, border: `1px solid ${KX2.glassLine}`,
          }}>Got it</button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { KxV2TeachSheet, KxV2LevelUp });
