/* ============================================================
   TRELLIS — Harvest board (AI work-triage, replaces "Kanban")
   Gmail + Calendar → Gemini → cards. Columns use growth language.
   Exports: HarvestPage
   ============================================================ */

const HARVEST_COLS = [
  { id: 'picked', label: 'Picked for you', hint: 'AI-suggested from Gmail + Calendar', icon: 'spark', hue: 248 },
  { id: 'rooted', label: 'Rooted', hint: 'Accepted onto your board', icon: 'sprout', hue: 330 },
  { id: 'tending', label: 'Tending', hint: 'In progress', icon: 'clock', hue: 96 },
  { id: 'harvested', label: 'Harvested', hint: 'Done', icon: 'check', hue: 155 }
];
const PRIO = { high: { tone: 'coral', c: 'var(--coral)' }, med: { tone: 'gold', c: 'var(--gold-deep)' }, low: { tone: 'leaf', c: 'var(--leaf)' } };
const SRC_ICON = { email: 'mail', calendar: 'calendar', system: 'spark' };
const SRC_LABEL = { email: 'Gmail', calendar: 'Calendar', system: 'Unstoppables flag' };

function HarvestCard({ c, onAccept, onDismiss, onAdvance, expanded, onToggle, onDragStart }) {
  const p = PRIO[c.priority];
  return (
    <div draggable={c.col !== 'picked'} onDragStart={e => onDragStart(e, c)}
      className="glass" style={{
        borderRadius: 18, padding: '14px 16px', cursor: 'pointer', position: 'relative',
        boxShadow: 'var(--shadow-card)', borderLeft: `3px solid ${p.c}`,
        transition: 'transform .2s var(--ease-spring)', animation: 'trellis-pop .35s var(--ease-spring)'
      }}
      onClick={onToggle}
      onMouseEnter={e => e.currentTarget.style.transform = 'translateY(-2px)'}
      onMouseLeave={e => e.currentTarget.style.transform = 'none'}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11, fontWeight: 700, letterSpacing: '.05em', textTransform: 'uppercase', color: 'var(--ink-faint)' }}>
          <Icon name={SRC_ICON[c.src]} size={13} /> {SRC_LABEL[c.src]}
        </span>
        {c.due && <span style={{ marginLeft: 'auto' }}><Badge tone={p.tone}>{c.due}</Badge></span>}
      </div>
      <div style={{ fontSize: 14, fontWeight: 700, lineHeight: 1.4 }}>{c.title}</div>
      {expanded && (
        <div style={{ marginTop: 10, animation: 'trellis-rise .25s ease' }}>
          <p className="t-soft" style={{ fontSize: 13, lineHeight: 1.55, margin: 0 }}>{c.desc}</p>
          <div style={{
            marginTop: 10, padding: '9px 12px', borderRadius: 12, background: 'var(--blue-soft)',
            fontSize: 12.5, lineHeight: 1.5, display: 'flex', gap: 8, alignItems: 'flex-start'
          }}>
            <Icon name="spark" size={14} style={{ color: 'var(--blue)', marginTop: 1 }} />
            <span><strong>Suggested:</strong> {c.action}</span>
          </div>
        </div>
      )}
      <div style={{ display: 'flex', gap: 8, marginTop: 12 }}>
        {c.col === 'picked' && (
          <React.Fragment>
            <button onClick={e => { e.stopPropagation(); onAccept(c); }} style={{
              flex: 1, padding: '8px 12px', borderRadius: 12, fontSize: 12.5, fontWeight: 700,
              background: 'var(--accent)', color: 'var(--accent-ink)', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6
            }}><Icon name="check" size={14} stroke={2.6} /> Accept</button>
            <button onClick={e => { e.stopPropagation(); onDismiss(c); }} style={{
              padding: '8px 14px', borderRadius: 12, fontSize: 12.5, fontWeight: 700,
              background: 'var(--hover)', border: '1px solid var(--hairline)', color: 'var(--ink-soft)',
              display: 'flex', alignItems: 'center', gap: 6
            }}><Icon name="x" size={13} stroke={2.4} /> Pass</button>
          </React.Fragment>
        )}
        {(c.col === 'rooted' || c.col === 'tending') && (
          <button onClick={e => { e.stopPropagation(); onAdvance(c); }} style={{
            flex: 1, padding: '8px 12px', borderRadius: 12, fontSize: 12.5, fontWeight: 700,
            background: 'var(--hover)', border: '1px solid var(--hairline)', color: 'var(--ink-soft)',
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6
          }}>{c.col === 'rooted' ? <React.Fragment><Icon name="clock" size={14} /> Start tending</React.Fragment> : <React.Fragment><Icon name="check" size={14} stroke={2.4} /> Mark harvested</React.Fragment>}</button>
        )}
      </div>
    </div>
  );
}

function HarvestPage({ push, params = {} }) {
  const [cards, setCards] = React.useState(window.TRELLIS_DATA.HARVEST);
  const [expanded, setExpanded] = React.useState(params.focus || null);
  const [crawling, setCrawling] = React.useState(false);
  const [lastSync, setLastSync] = React.useState('11:32');
  const dragCard = React.useRef(null);

  React.useEffect(() => { if (params.focus) setExpanded(params.focus); }, [params.focus]);

  const move = (card, col) => setCards(cs => cs.map(c => c.id === card.id ? { ...c, col } : c));

  const accept = c => { move(c, 'rooted'); push('Rooted on your board — Calendar reminder set ✓'); };
  const dismiss = c => { setCards(cs => cs.filter(x => x.id !== c.id)); push('Passed — the agent won\u2019t suggest this again'); };
  const advance = c => {
    if (c.col === 'rooted') { move(c, 'tending'); push('Moved to Tending'); }
    else { move(c, 'harvested'); push('Harvested 🎉 Nice work'); }
  };
  const crawl = () => {
    setCrawling(true);
    setTimeout(() => {
      setCrawling(false);
      setLastSync(new Date().toLocaleTimeString('en-CA', { hour: '2-digit', minute: '2-digit', hour12: false }));
      push('Harvest agent crawled Gmail + Calendar — board is fresh');
    }, 1600);
  };
  const onDragStart = (e, c) => { dragCard.current = c; e.dataTransfer.effectAllowed = 'move'; };
  const onDropCol = (colId) => { if (dragCard.current && dragCard.current.col !== 'picked') { move(dragCard.current, colId); dragCard.current = null; } };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20, height: '100%' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', gap: 16, flexWrap: 'wrap' }}>
        <div>
          <h1 style={{ fontSize: 'clamp(24px, 3.4vw, 32px)', fontWeight: 700, letterSpacing: '-0.025em', display: 'flex', alignItems: 'center', gap: 12 }}>
            Harvest
            <Badge tone="blue"><Icon name="spark" size={13} /> Gemini agent</Badge>
          </h1>
          <p className="t-soft" style={{ margin: '6px 0 0', fontSize: 14.5 }}>
            Your inbox and calendar, picked daily. Accept a card and the reminder lands in Google Calendar.
          </p>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <span className="t-faint mono" style={{ fontSize: 12 }}>last crawl {lastSync}</span>
          <button onClick={crawl} disabled={crawling} className="glass" style={{
            padding: '10px 18px', borderRadius: 14, fontSize: 13.5, fontWeight: 700,
            display: 'flex', alignItems: 'center', gap: 8, opacity: crawling ? 0.7 : 1
          }}>
            <span style={{ display: 'inline-flex', animation: crawling ? 'spin 1s linear infinite' : 'none' }}>
              <Icon name="refresh" size={15} stroke={2.2} />
            </span>
            {crawling ? 'Crawling…' : 'Re-crawl now'}
          </button>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(250px, 1fr))', gap: 14, alignItems: 'start' }}>
        {HARVEST_COLS.map(col => {
          const colCards = cards.filter(c => c.col === col.id);
          return (
            <div key={col.id}
              onDragOver={e => e.preventDefault()}
              onDrop={() => onDropCol(col.id)}
              style={{ display: 'flex', flexDirection: 'column', gap: 10, minHeight: 200 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 9, padding: '4px 6px' }}>
                <span style={{
                  width: 26, height: 26, borderRadius: 9, display: 'grid', placeItems: 'center',
                  background: `oklch(0.68 0.12 ${col.hue} / 0.16)`, color: `oklch(0.55 0.13 ${col.hue})`
                }}><Icon name={col.icon} size={14} stroke={2.2} /></span>
                <div>
                  <div style={{ fontFamily: 'var(--font-display)', fontSize: 13.5, fontWeight: 700 }}>{col.label}
                    <span className="mono t-faint" style={{ fontWeight: 500, marginLeft: 7, fontSize: 11.5 }}>{colCards.length}</span>
                  </div>
                  <div className="t-faint" style={{ fontSize: 10.5, fontWeight: 600 }}>{col.hint}</div>
                </div>
              </div>
              {colCards.map(c => (
                <HarvestCard key={c.id} c={c}
                  onAccept={accept} onDismiss={dismiss} onAdvance={advance}
                  expanded={expanded === c.id}
                  onToggle={() => setExpanded(expanded === c.id ? null : c.id)}
                  onDragStart={onDragStart} />
              ))}
              {colCards.length === 0 && (
                <div style={{
                  borderRadius: 16, border: '1.5px dashed var(--hairline-strong)', padding: '26px 14px',
                  textAlign: 'center', fontSize: 12.5, color: 'var(--ink-faint)', fontWeight: 600
                }}>Drop cards here</div>
              )}
            </div>
          );
        })}
      </div>
      <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
    </div>
  );
}

Object.assign(window, { HarvestPage });
