// The Wish Box: Sarah's ideas for the Workshop or her games. A big card on
// the dashboard and a page to write (or dictate, with the iPad keyboard's mic)
// a wish, see Professor Hoot's thanks, and follow each wish:
// sent -> "Dad's working on it" -> done!

const WISH_STATUS = {
  sent: { label: 'Sent', icon: '📨', cls: 'sent' },
  working: { label: "Dad's working on it", icon: '🔨', cls: 'working' },
  done: { label: 'Done!', icon: '🎉', cls: 'done' }
};
const WISH_ABOUT = [
  ['workshop', '🛠️', 'The Workshop'],
  ['dragon', '🐉', 'Dragon Caretaker'],
  ['other', '💡', 'Something else']
];

function wishDate(d) {
  const t = new Date(d);
  return isNaN(t) ? '' : t.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
}

function WishBoxCard({ onOpen }) {
  const [wishes, setWishes] = useState(null);
  useEffect(() => { api('/api/wishes').then(d => setWishes(d && d.wishes ? d.wishes : [])); }, []);
  const n = wishes ? wishes.length : 0;
  const working = wishes ? wishes.filter(w => w.status === 'working').length : 0;
  const done = wishes ? wishes.filter(w => w.status === 'done').length : 0;
  return (
    <button className="wish-card" onClick={onOpen}>
      <div className="wish-card-art"><Hoot pose="wish" size={110} /></div>
      <div className="wish-card-body">
        <h2>✨ Wish Box</h2>
        <p>Got an idea for the Workshop or your games? Tell Professor Hoot!</p>
        {n > 0 && (
          <div className="wish-card-summary">
            {n} wish{n === 1 ? '' : 'es'} sent{working ? ` · ${working} being built` : ''}{done ? ` · ${done} done!` : ''}
          </div>
        )}
        <span className="wish-card-cta">Make a wish →</span>
      </div>
    </button>
  );
}

function WishBoxPage({ onBack }) {
  const voice = useHootVoice();
  const [wishes, setWishes] = useState(null);
  const [text, setText] = useState('');
  const [about, setAbout] = useState('workshop');
  const [sending, setSending] = useState(false);
  const [problem, setProblem] = useState('');
  const [thanks, setThanks] = useState(null);
  const [badges, setBadges] = useState(null);

  const load = useCallback(async () => {
    const d = await api('/api/wishes');
    setWishes(d && d.wishes ? d.wishes : []);
  }, []);
  useEffect(() => { load(); }, [load]);

  const send = async () => {
    if (!text.trim() || sending) return;
    setSending(true);
    setProblem('');
    const d = await api('/api/wishes', { method: 'POST', body: { text, about } });
    setSending(false);
    if (!d || d.error) {
      setProblem((d && d.message) || 'Oops, the wish didn’t send. Try again in a moment!');
      return;
    }
    setText('');
    setThanks(voice.line('wish_thanks') || { text: 'Wish received! I’m flying it to Dad right now!' });
    setWishes(w => [d.wish, ...(w || [])]);
    if (d.badgesEarned && d.badgesEarned.length) setBadges(d.badgesEarned);
  };

  return (
    <div className="craft-page wish-page">
      <div className="explorer-header" style={{ background: 'linear-gradient(135deg, #FF6B6B, #FFB86B)' }}>
        <ExplorerImage className="explorer-header-img" src="/images/headers/wish-box.webp" emoji="✨" size="4rem" />
        <button className="back-btn header-back" onClick={onBack}>← Workshop</button>
        <h1>✨ Wish Box</h1>
      </div>
      <div className="craft-content">
        <HootSays pool="wish_intro" pose="wish" size={96} />
        <div className="wish-form">
          <label htmlFor="wish-text" className="wish-label">My wish:</label>
          <textarea id="wish-text" className="wish-text" rows={4} maxLength={1000}
            autoCapitalize="sentences" spellCheck="true"
            placeholder="I wish the Workshop had…"
            value={text} onChange={e => setText(e.target.value)} />
          <div className="wish-tip">Tip: tap the 🎤 on the keyboard and say your wish out loud!</div>
          <div className="wish-about-label">It's for:</div>
          <div className="wish-about">
            {WISH_ABOUT.map(([key, icon, label]) => (
              <button key={key} className={`wish-chip ${about === key ? 'on' : ''}`} onClick={() => setAbout(key)}
                aria-pressed={about === key}>{icon} {label}</button>
            ))}
          </div>
          {problem && <div className="wish-problem">{problem}</div>}
          <button className="btn-primary big wish-send" onClick={send} disabled={!text.trim() || sending}>
            {sending ? 'Sending…' : 'Send my wish ✨'}
          </button>
        </div>

        <h2 className="section-title">My wishes</h2>
        {wishes === null && <div className="quiz-loading">Loading…</div>}
        {wishes && wishes.length === 0 && <div className="empty-note">No wishes yet. Your first one will show up here!</div>}
        {wishes && wishes.length > 0 && (
          <ul className="wish-list">
            {wishes.map(w => {
              const st = WISH_STATUS[w.status] || WISH_STATUS.sent;
              const ab = WISH_ABOUT.find(a => a[0] === w.about);
              return (
                <li key={w.id} className="wish-item">
                  <div className="wish-item-text">{w.text}</div>
                  <div className="wish-item-meta">
                    <span className={`wish-status ${st.cls}`}>{st.icon} {st.label}</span>
                    <span className="wish-item-date">{ab ? ab[1] + ' ' : ''}{wishDate(w.created_at)}</span>
                  </div>
                </li>
              );
            })}
          </ul>
        )}
      </div>

      {thanks && (
        <div className="badge-popup-overlay" onClick={() => setThanks(null)}>
          <div className="badge-popup wish-thanks" onClick={e => e.stopPropagation()}>
            <Hoot pose="wish" size={130} />
            <h3>Wish sent!</h3>
            <div className="desc">{thanks.text}</div>
            {thanks.key && <SpeakButton voiceKey={thanks.key} label="Hear Hoot" />}
            <button className="btn-primary" onClick={() => setThanks(null)}>Yay!</button>
          </div>
          <Confetti count={40} />
        </div>
      )}
      {!thanks && <BadgeQueue badges={badges} onDone={() => setBadges(null)} />}
    </div>
  );
}
