// Playbook detail: header + snip composer + dashboard + timeline + destinations
const { useState: useStatePD, useEffect: useEffectPD, useMemo: useMemoPD, useRef: useRefPD } = React;

function PlaybookDetail({ playbook, openCity }) {
  const store = useStore();
  const user = store.getCurrentUser();
  const [tab, setTab] = useStatePD('dashboard'); // dashboard | timeline | destinations | goals
  const [suggestion, setSuggestion] = useStatePD(null);
  const [loadingSugg, setLoadingSugg] = useStatePD(false);
  const [editingTitle, setEditingTitle] = useStatePD(false);

  const refreshSuggestion = async () => {
    setLoadingSugg(true);
    try {
      const s = await window.proactiveSuggestion(playbook, user.profile);
      setSuggestion(s);
    } catch { setSuggestion("Claude's offline — try again later."); }
    setLoadingSugg(false);
  };

  useEffectPD(() => { refreshSuggestion(); }, [playbook.id, playbook.snips.length, playbook.destinations.length]);

  return (
    <div className="pb-detail">
      <div className="pb-detail-head">
        <div className="pb-head-main">
          <div className="loc-kicker">PLAYBOOK · CREATED {new Date(playbook.createdAt).toLocaleDateString()}</div>
          {editingTitle ? (
            <input className="pb-title-input" autoFocus defaultValue={playbook.title}
              onBlur={e => { store.updatePlaybook(playbook.id, { title: e.target.value || 'Untitled' }); setEditingTitle(false); }}
              onKeyDown={e => { if (e.key === 'Enter') e.target.blur(); }}/>
          ) : (
            <h1 className="pb-title" onClick={() => setEditingTitle(true)}>{playbook.title} <span className="pencil">✎</span></h1>
          )}
          <div className="pb-dest-strip">
            {playbook.destinations.length === 0 && <span className="muted">No destinations · use the map to add hubs, or add a manual stop below.</span>}
            {playbook.destinations.map((d, i) => (
              <span key={d.id} className="pb-dest-chip">
                {i > 0 && <span className="arrow">→</span>}
                <span className="pb-dest-label">{d.label}</span>
                <span className="pb-dest-when">{d.arrival || 'TBD'}</span>
              </span>
            ))}
          </div>
        </div>
        <div className="pb-head-actions">
          <button className="loc-tag-btn" onClick={() => { if (confirm('Delete this playbook?')) store.deletePlaybook(playbook.id); }}>Delete</button>
        </div>
      </div>

      <ProactiveCard text={suggestion} loading={loadingSugg} onRefresh={refreshSuggestion}/>

      <SnipComposer playbook={playbook} profile={user.profile}/>

      <div className="pb-tabs">
        <button className={`pb-tab ${tab === 'dashboard' ? 'on' : ''}`} onClick={() => setTab('dashboard')}>Dashboard</button>
        <button className={`pb-tab ${tab === 'bookings' ? 'on' : ''}`} onClick={() => setTab('bookings')}>Bookings</button>
        <button className={`pb-tab ${tab === 'timeline' ? 'on' : ''}`} onClick={() => setTab('timeline')}>Timeline</button>
        <button className={`pb-tab ${tab === 'destinations' ? 'on' : ''}`} onClick={() => setTab('destinations')}>Destinations <span className="tab-count">{playbook.destinations.length}</span></button>
        <button className={`pb-tab ${tab === 'goals' ? 'on' : ''}`} onClick={() => setTab('goals')}>Goals <span className="tab-count">{playbook.goals.length}</span></button>
      </div>

      {tab === 'dashboard' && <SnipDashboard playbook={playbook}/>}
      {tab === 'bookings' && <BookingsHub playbook={playbook}/>}
      {tab === 'timeline' && <PlaybookTimeline playbook={playbook}/>}
      {tab === 'destinations' && <DestinationManager playbook={playbook} openCity={openCity}/>}
      {tab === 'goals' && <GoalManager playbook={playbook}/>}
    </div>
  );
}

function ProactiveCard({ text, loading, onRefresh }) {
  return (
    <div className="proactive-card">
      <div className="proactive-mark">
        <span className="ai-dot"></span>
        <span>CLAUDE · NEXT MOVE</span>
      </div>
      <div className="proactive-body">
        {loading ? <span className="muted">thinking…</span> : (text || 'Add a destination or paste research to get a suggestion.')}
      </div>
      <button className="proactive-refresh" onClick={onRefresh} title="Re-run">↻</button>
    </div>
  );
}

function SnipComposer({ playbook, profile }) {
  const store = useStore();
  const [val, setVal] = useStatePD('');
  const [pending, setPending] = useStatePD(false);

  const submit = async () => {
    const text = val.trim();
    if (!text) return;
    setPending(true);
    try {
      const meta = await window.classifySnip(text, profile, playbook.destinations);
      // attach to destination by label match
      const dest = playbook.destinations.find(d => meta.destinationLabel && d.label.toLowerCase().includes(meta.destinationLabel.toLowerCase()));
      store.addSnip(playbook.id, {
        type: meta.type || 'note',
        title: meta.title || text.slice(0, 60),
        body: meta.body || '',
        url: meta.url || (text.match(/https?:\/\/\S+/) ? text.match(/https?:\/\/\S+/)[0] : null),
        price: meta.price ?? null,
        currency: meta.currency || null,
        when: meta.when || null,
        destinationId: dest?.id || null,
        destinationLabel: meta.destinationLabel || dest?.label || null,
        tags: meta.tags || [],
        raw: text,
      });
      setVal('');
    } catch (e) {
      // fallback: still add as note
      store.addSnip(playbook.id, { type: 'note', title: text.slice(0, 60), body: text, raw: text });
      setVal('');
    }
    setPending(false);
  };

  return (
    <div className="snip-composer">
      <div className="snip-composer-head">
        <span className="ai-dot"></span>
        <span>SNIP — paste a link, flight #, hostel name, contact, anything. Claude sorts it.</span>
      </div>
      <div className="snip-composer-row">
        <textarea className="snip-input" rows="2"
          placeholder="e.g.  https://www.skyscanner.com/...   |   AirBnB Lisbon Sep 4–28 €1,840   |   Maria @ Cowork Lisboa, m@…"
          value={val} onChange={e => setVal(e.target.value)}
          onKeyDown={e => { if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) submit(); }}/>
        <button className="snip-submit" onClick={submit} disabled={pending || !val.trim()}>
          {pending ? 'Sorting…' : 'Snip →'}
        </button>
      </div>
    </div>
  );
}

window.PlaybookDetail = PlaybookDetail;
