// ai-assistant.jsx — floating bilingual AI front-desk widget for the prototype

function AIAssistant({ dark, lang, headingFont }) {
  const p = palette(dark);
  const en = lang === 'en';

  const [open, setOpen] = React.useState(false);
  const [input, setInput] = React.useState('');
  const [sending, setSending] = React.useState(false);
  const [messages, setMessages] = React.useState(() => ([
    {
      role: 'assistant',
      text: en
        ? "Hi, I'm Aria — Mastery's front desk assistant. I can help with programs, tuition, scheduling a trial, or finding the right teacher. What can I help with?"
        : "你好，我是 Aria，Mastery 的前台助理。我可以介绍课程、学费、安排试听课，或帮你匹配老师。请问有什么可以帮你？",
    },
  ]));

  const scrollerRef = React.useRef(null);
  React.useEffect(() => {
    if (scrollerRef.current) scrollerRef.current.scrollTop = scrollerRef.current.scrollHeight;
  }, [messages, open]);

  // Reset greeting when language flips
  React.useEffect(() => {
    setMessages([{
      role: 'assistant',
      text: en
        ? "Hi, I'm Aria — Mastery's front desk assistant. I can help with programs, tuition, scheduling a trial, or finding the right teacher. What can I help with?"
        : "你好，我是 Aria，Mastery 的前台助理。我可以介绍课程、学费、安排试听课，或帮你匹配老师。请问有什么可以帮你？",
    }]);
  }, [lang]);

  const suggestions = en ? [
    'How does the trial lesson work?',
    "What's the tuition for piano?",
    'My child is 6 — which program fits?',
    'Do you offer makeup lessons?',
  ] : [
    '试听课怎么进行？',
    '钢琴课学费多少？',
    '孩子 6 岁，适合哪个课程？',
    '可以补课吗？',
  ];

  // Mock-y, deterministic response logic (no real LLM call — pure prototype)
  function fakeReply(q) {
    const lc = q.toLowerCase();
    if (en) {
      if (/trial|试听/.test(lc)) return "A trial is a 30-min paid lesson with the matched teacher. The fee is credited to your first month if you enroll within 14 days. Want me to find a slot this week?";
      if (/tuition|fee|price|cost|学费|价格/.test(lc)) return "Private lessons start at $48 per 30 min, group classes from $32 per 60 min. I can show you the full sheet on the Programs page — want the link?";
      if (/age|6|7|kid|child|孩子/.test(lc)) return "For ages 5–8 we usually start with a 30-min private lesson plus a small group ear-training class. Two faculty match well — want me to suggest a trial?";
      if (/makeup|reschedule|补课/.test(lc)) return "Yes — parents can request a makeup directly from the parent portal. Two per term are included; extras are a small fee.";
      if (/teacher|faculty|老师/.test(lc)) return "I can match a teacher by instrument, age, and style (classical / pop / exam track). What instrument is your child interested in?";
      return "Good question — I'll loop in our admin team and get back within an hour. In the meantime, here's our trial booking page.";
    } else {
      if (/试听|trial/.test(lc)) return "试听课为 30 分钟付费课程，由匹配的教师授课。14 天内注册可抵首月学费。要不要看看本周可预约的时段？";
      if (/学费|价格|多少钱|tuition|fee|price/.test(lc)) return "私人课从 30 分钟 ¥48 起；小组课从 60 分钟 ¥32 起。完整价目表在「课程」页面，需要链接吗？";
      if (/孩子|岁|age|kid|child/.test(lc)) return "5–8 岁通常建议 30 分钟私人课 + 小组视唱练耳。我们有两位老师比较合适，要安排一节试听课吗？";
      if (/补课|makeup|reschedule/.test(lc)) return "可以，家长可以在家长 Portal 直接申请补课。每学期免费两次，多出的需小额补差。";
      if (/老师|教师|teacher|faculty/.test(lc)) return "我可以按乐器、年龄、风格（古典 / 流行 / 考级）来匹配老师。请问孩子想学什么乐器？";
      return "好的，我会把这个问题转给前台同事，1 小时内回复你。先附上试听预约链接，方便随时安排。";
    }
  }

  function send(text) {
    const q = (text || input).trim();
    if (!q || sending) return;
    setMessages(m => [...m, { role: 'user', text: q }]);
    setInput('');
    setSending(true);
    // simulate latency
    setTimeout(() => {
      setMessages(m => [...m, { role: 'assistant', text: fakeReply(q) }]);
      setSending(false);
    }, 700);
  }

  // ── Floating launcher ─────────────────────────────────
  const launcher = (
    <button
      onClick={() => setOpen(o => !o)}
      style={{
        position: 'fixed', right: 24, bottom: 24, zIndex: 9999,
        width: 64, height: 64, borderRadius: 32,
        background: p.gold, color: dark ? '#15140F' : '#FFF',
        border: 'none', cursor: 'pointer',
        boxShadow: '0 14px 36px rgba(0,0,0,0.28)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontFamily: TOKENS.font.serif, fontSize: 26, fontStyle: 'italic',
        fontWeight: 500,
        transition: 'transform .2s ease',
        transform: open ? 'scale(0.92)' : 'scale(1)',
      }}
      aria-label={en ? 'Open assistant' : '打开助理'}
      title={en ? 'Ask Aria' : '问 Aria'}
    >
      {open ? '×' : 'A'}
    </button>
  );

  if (!open) return launcher;

  // ── Panel ─────────────────────────────────────────────
  return (
    <React.Fragment>
      {launcher}
      <div style={{
        position: 'fixed', right: 24, bottom: 100, zIndex: 9998,
        width: 380, height: 560,
        background: p.paper, color: p.ink,
        border: `0.5px solid ${p.line}`,
        borderRadius: 16,
        boxShadow: '0 30px 80px rgba(0,0,0,0.32)',
        display: 'flex', flexDirection: 'column', overflow: 'hidden',
        fontFamily: TOKENS.font.sans,
      }}>

        {/* Header */}
        <div style={{
          padding: '18px 20px',
          borderBottom: `0.5px solid ${p.line}`,
          background: p.paperSoft,
          display: 'flex', alignItems: 'center', gap: 12,
        }}>
          <div style={{
            width: 36, height: 36, borderRadius: 18,
            background: p.gold, color: dark ? '#15140F' : '#FFF',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontFamily: TOKENS.font.serif, fontStyle: 'italic', fontSize: 18, fontWeight: 600,
          }}>A</div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 14, fontWeight: 600, color: p.ink }}>
              Aria · {en ? 'Front desk assistant' : '前台助理'}
            </div>
            <div style={{ fontSize: 11, color: p.inkMuted, marginTop: 2, display: 'flex', alignItems: 'center', gap: 6 }}>
              <span style={{ width: 6, height: 6, borderRadius: 3, background: '#4E9560', display: 'inline-block' }} />
              {en ? 'Online · usually replies instantly' : '在线 · 通常即时回复'}
            </div>
          </div>
        </div>

        {/* Messages */}
        <div ref={scrollerRef} style={{
          flex: 1, overflowY: 'auto', padding: '18px 16px',
          background: p.paper,
        }}>
          {messages.map((m, i) => (
            <div key={i} style={{
              display: 'flex',
              justifyContent: m.role === 'user' ? 'flex-end' : 'flex-start',
              marginBottom: 12,
            }}>
              <div style={{
                maxWidth: '78%',
                padding: '10px 14px',
                borderRadius: 12,
                background: m.role === 'user'
                  ? p.gold
                  : (dark ? p.paperSoft : '#FFF'),
                color: m.role === 'user'
                  ? (dark ? '#15140F' : '#FFF')
                  : p.ink,
                border: m.role === 'user' ? 'none' : `0.5px solid ${p.line}`,
                fontSize: 13.5,
                lineHeight: 1.55,
                whiteSpace: 'pre-wrap',
              }}>{m.text}</div>
            </div>
          ))}

          {sending && (
            <div style={{ display: 'flex', justifyContent: 'flex-start', marginBottom: 12 }}>
              <div style={{
                padding: '10px 14px', borderRadius: 12,
                background: dark ? p.paperSoft : '#FFF',
                border: `0.5px solid ${p.line}`,
                color: p.inkMuted, fontSize: 13,
                display: 'flex', gap: 4, alignItems: 'center',
              }}>
                <Dot d={0} /><Dot d={150} /><Dot d={300} />
              </div>
            </div>
          )}

          {messages.length <= 1 && !sending && (
            <div style={{ marginTop: 8 }}>
              <div style={{ fontSize: 11, color: p.inkMuted, marginBottom: 8, letterSpacing: 0.6, textTransform: 'uppercase' }}>
                {en ? 'Try asking' : '试试问'}
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                {suggestions.map((s, i) => (
                  <button key={i} onClick={() => send(s)} style={{
                    textAlign: 'left',
                    padding: '8px 12px',
                    background: 'transparent',
                    border: `0.5px solid ${p.line}`,
                    borderRadius: 10,
                    color: p.inkSoft,
                    fontSize: 12.5,
                    cursor: 'pointer',
                    fontFamily: TOKENS.font.sans,
                  }}>{s}</button>
                ))}
              </div>
            </div>
          )}
        </div>

        {/* Footer note */}
        <div style={{
          padding: '6px 16px',
          borderTop: `0.5px solid ${p.line}`,
          background: p.paperSoft,
          fontSize: 10,
          color: p.inkMuted,
          letterSpacing: 0.4,
          textAlign: 'center',
        }}>
          {en ? 'Custom AI agent · powered by frontier models (OpenAI, Claude…)' : '定制 AI 智能体 · 由 OpenAI、Claude 等顶尖大模型驱动'}
        </div>

        {/* Input */}
        <form onSubmit={(e) => { e.preventDefault(); send(); }} style={{
          padding: 12,
          borderTop: `0.5px solid ${p.line}`,
          background: p.paper,
          display: 'flex', gap: 8,
        }}>
          <input
            value={input}
            onChange={(e) => setInput(e.target.value)}
            placeholder={en ? 'Ask about programs, tuition, trials…' : '问问课程、学费、试听…'}
            style={{
              flex: 1,
              padding: '10px 12px',
              borderRadius: 10,
              border: `0.5px solid ${p.line}`,
              background: dark ? p.paperSoft : '#FFF',
              color: p.ink,
              fontSize: 13,
              outline: 'none',
              fontFamily: TOKENS.font.sans,
            }}
          />
          <button type="submit" disabled={!input.trim() || sending} style={{
            padding: '0 16px',
            borderRadius: 10,
            border: 'none',
            background: input.trim() && !sending ? p.gold : p.paperSoft,
            color: input.trim() && !sending ? (dark ? '#15140F' : '#FFF') : p.inkMuted,
            fontSize: 13, fontWeight: 600,
            cursor: input.trim() && !sending ? 'pointer' : 'default',
            fontFamily: TOKENS.font.sans,
          }}>{en ? 'Send' : '发送'}</button>
        </form>
      </div>
    </React.Fragment>
  );
}

function Dot({ d }) {
  return (
    <span style={{
      width: 6, height: 6, borderRadius: 3, background: 'currentColor',
      display: 'inline-block', opacity: 0.5,
      animation: `aria-pulse 1.2s ease-in-out ${d}ms infinite`,
    }} />
  );
}

// inject keyframes once
(function injectAriaCSS() {
  if (document.getElementById('aria-kf')) return;
  const s = document.createElement('style');
  s.id = 'aria-kf';
  s.textContent = '@keyframes aria-pulse { 0%, 80%, 100% { opacity: 0.25; transform: translateY(0); } 40% { opacity: 1; transform: translateY(-2px); } }';
  document.head.appendChild(s);
})();

window.AIAssistant = AIAssistant;
