/* the turn - Field Guide. The library: the 13 species the app knows.
   Phone-first list (grid on wide), status pips, lure tier, season countdowns,
   plus two cross-cutting cards (food web, ethics). */

/* days until a date string like "1 Oct" / "1 Dec" from 8 Jun 2026 */
function daysUntil(until) {
  if (!until) return null;
  const months = { Jan: 0, Feb: 1, Mar: 2, Apr: 3, May: 4, Jun: 5, Jul: 6, Aug: 7, Sep: 8, Oct: 9, Nov: 10, Dec: 11 };
  const [d, m] = until.split(' ');
  const now = new Date(2026, 5, 8);
  let target = new Date(2026, months[m], parseInt(d, 10));
  if (target < now) target = new Date(2027, months[m], parseInt(d, 10));
  return Math.round((target - now) / 86400000);
}

function SpeciesCard({ sp, onSpecies }) {
  const days = sp.season.open ? null : daysUntil(sp.season.until);
  return (
    <button onClick={() => onSpecies(sp.id)} style={{
      display: 'block', width: '100%', minWidth: 0, maxWidth: '100%', overflow: 'hidden', textAlign: 'left', cursor: 'pointer',
      background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-md)', padding: 'var(--space-4)',
    }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 14, minWidth: 0 }}>
        <span style={{ flex: '0 0 auto', width: 52, height: 52, borderRadius: 'var(--r-sm)', background: 'var(--bg)', border: '1px solid var(--border)', display: 'grid', placeItems: 'center' }}>
          <FishIcon species={sp.id} size={40} color="var(--text)" />
        </span>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 10 }}>
            <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 18, color: 'var(--text)', lineHeight: 1.1, flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{sp.common}</span>
            <span style={{ flex: '0 0 auto' }}><LureTier tier={sp.lure} /></span>
          </div>
          <div style={{ fontStyle: 'italic', fontSize: 12.5, color: 'var(--text-label)', marginTop: 1 }}>{sp.sci}</div>
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 10 }}>
            <SassiPip status={sp.sassi} />
            <IucnPip status={sp.iucn} />
            <SeasonPip season={sp.season} />
          </div>
        </div>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, borderTop: '1px solid var(--hairline)', marginTop: 12, paddingTop: 10, minWidth: 0 }}>
        <span style={{ fontSize: 13, color: 'var(--text-dim)', lineHeight: 1.35, flex: 1, minWidth: 0, overflowWrap: 'break-word' }}>{sp.habitat}</span>
        {days != null && (
          <span style={{ flex: '0 0 auto', fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '.04em', textTransform: 'uppercase', color: 'var(--verdict-caution)', border: '1px solid var(--verdict-caution)', borderRadius: 'var(--r-pill)', padding: '3px 8px', whiteSpace: 'nowrap' }}>
            opens {sp.season.until} · {days}d
          </span>
        )}
      </div>
    </button>
  );
}

function CrossCard({ icon, title, sub, onClick }) {
  return (
    <button onClick={onClick} style={{ display: 'flex', flexDirection: 'column', gap: 10, flex: 1, minWidth: 0, padding: '14px', background: 'var(--surface-sunk)', border: '1px solid var(--border)', borderRadius: 'var(--r-md)', cursor: 'pointer', textAlign: 'left' }}>
      <span style={{ flex: '0 0 auto', width: 34, height: 34, borderRadius: '50%', background: 'var(--surface)', border: '1px solid var(--border-strong)', display: 'grid', placeItems: 'center', color: 'var(--text-dim)' }}>{icon}</span>
      <span style={{ minWidth: 0 }}>
        <span style={{ display: 'block', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 14, color: 'var(--text)', lineHeight: 1.15 }}>{title}</span>
        <span style={{ display: 'block', fontSize: 11.5, color: 'var(--text-label)', marginTop: 3, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{sub}</span>
      </span>
    </button>
  );
}

function FieldGuide({ onSpecies, wide = false }) {
  const { useState, useMemo } = React;
  const T = window.TURN;
  const [status, setStatus] = useState('any');
  const [season, setSeason] = useState('any');

  const scoutedAreaIds = useMemo(() => new Set(T.areas.filter(a => a.lifecycle !== 'none').map(a => a.id)), []);
  const [foundIn, setFoundIn] = useState('any');

  const list = useMemo(() => T.species.filter(sp => {
    if (status !== 'any' && sp.sassi !== status) return false;
    if (season === 'open' && !sp.season.open) return false;
    if (season === 'closed' && sp.season.open) return false;
    if (foundIn === 'scouted' && !sp.areas.some(id => scoutedAreaIds.has(id))) return false;
    return true;
  }), [status, season, foundIn]);

  return (
    <div style={{ padding: '4px var(--gutter) 0', display: 'flex', flexDirection: 'column', gap: 14 }}>
      <div>
        <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 22, color: 'var(--text)', letterSpacing: '-0.02em' }}>Field Guide</div>
        <div className="overline" style={{ marginTop: 2 }}>species · {T.species.length}</div>
      </div>

      {/* cross-cutting */}
      <div style={{ display: 'flex', gap: 10 }}>
        <CrossCard onClick={() => onSpecies('_foodweb')} title="Walker Bay food web" sub="who eats what, and why it matters"
          icon={<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><circle cx="6" cy="7" r="2.5" /><circle cx="17" cy="9" r="2.5" /><circle cx="11" cy="17" r="2.5" /><path d="M8 8l7 1M15 11l-3 4M9 9l1 6" /></svg>} />
        <CrossCard onClick={() => onSpecies('_ethics')} title="Angler ethics" sub="handle, release, leave it better"
          icon={<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 4s6 2 6 7c0 5-6 9-6 9s-6-4-6-9c0-5 6-7 6-7z" /></svg>} />
      </div>

      {/* filters */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
        <FilterRow label="SASSI" value={status} onChange={setStatus} options={[{ value: 'any', label: 'any' }, { value: 'green', label: 'Green' }, { value: 'orange', label: 'Orange' }, { value: 'red', label: 'Red' }]} />
        <FilterRow label="season" value={season} onChange={setSeason} options={[{ value: 'any', label: 'any' }, { value: 'open', label: 'in season' }, { value: 'closed', label: 'closed' }]} />
        <FilterRow label="where" value={foundIn} onChange={setFoundIn} options={[{ value: 'any', label: 'anywhere' }, { value: 'scouted', label: 'areas you\u2019ve scouted' }]} />
      </div>

      {/* list */}
      <div className="fg-grid" style={{ display: 'grid', gridTemplateColumns: wide ? 'repeat(2, 1fr)' : '1fr', gap: 10 }}>
        {list.map(sp => <SpeciesCard key={sp.id} sp={sp} onSpecies={onSpecies} />)}
      </div>
      {list.length === 0 && <div style={{ padding: 24, textAlign: 'center', color: 'var(--text-label)', fontSize: 14 }}>nothin' biting those filters, mate</div>}
      <div style={{ height: 8 }} />
    </div>
  );
}

Object.assign(window, { FieldGuide, daysUntil });
