/* the turn - Log. The memory: capture trips, browse history, learn.
   History list with frozen observation badges + the full new-log form. */
const { Button: LgButton, Chip: LgChip } = window.TheTurnDesignSystem_583d9e;

const OUTCOME = {
  went:    { c: 'var(--verdict-go)',   label: 'went' },
  skipped: { c: 'var(--verdict-dont)', label: 'skipped' },
  aborted: { c: 'var(--verdict-caution)', label: 'aborted' },
};
const OBS_TONE = {
  mouth: 'var(--text-dim)', water: 'var(--text-dim)', bait: 'var(--text-dim)',
};
function obsLabel(k, v) { return v; }

function ObsBadge({ kind, value }) {
  if (!value || value === 'unknown') return null;
  const tone = kind === 'water' && (value === 'clean') ? 'var(--verdict-go)'
    : kind === 'mouth' && value === 'open' ? 'var(--verdict-go)'
    : (value === 'dirty' || value === 'closed' || value === 'nothing-seen') ? 'var(--text-label)'
    : 'var(--text-dim)';
  return <StatusPip label={value} tone={tone} dot={null} style={{ height: 22, fontSize: 10 }} />;
}

/* ---- one history row ---- */
function LogRow({ log, onLog, onArea }) {
  const area = areaById(log.areaId);
  const o = OUTCOME[log.outcome];
  return (
    <button onClick={() => onLog(log.id)} style={{ display: 'block', width: '100%', 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: 'center', gap: 10 }}>
        <span style={{ width: 11, height: 11, borderRadius: '50%', background: o.c, flex: '0 0 auto' }} />
        <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 17, color: 'var(--text)', flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{area ? area.name : log.areaId}</span>
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--text-label)', flex: '0 0 auto' }}>{log.when}</span>
      </div>
      {log.outcome === 'went' && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, margin: '10px 0 0', flexWrap: 'wrap' }}>
          <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '.06em', textTransform: 'uppercase', color: o.c }}>{o.label}</span>
          <span style={{ color: 'var(--text-label)' }}>·</span>
          <span className="metric" style={{ fontSize: 12.5, color: 'var(--text-dim)' }}>{PLATFORM_LABEL[log.platform]} · {METHOD_LABEL[log.method]}</span>
          {log.tackle && <span style={{ fontSize: 12.5, color: 'var(--text-label)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>· {log.tackle}</span>}
        </div>
      )}
      {log.outcome !== 'went' && (
        <div style={{ margin: '10px 0 0' }}><span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '.06em', textTransform: 'uppercase', color: o.c }}>{o.label}</span></div>
      )}
      {log.result && <div style={{ fontSize: 14, color: 'var(--text)', marginTop: 8, lineHeight: 1.35 }}>{log.result}</div>}
      {/* observation badges */}
      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 10 }}>
        {log.species && log.species.map(id => <SpeciesChip key={id} id={id} color="var(--verdict-go)" style={{ height: 22, fontSize: 11, padding: '0 9px 0 7px' }} />)}
        {log.obs && <ObsBadge kind="mouth" value={log.obs.mouth} />}
        {log.obs && <ObsBadge kind="water" value={log.obs.water} />}
        {log.obs && <ObsBadge kind="bait" value={log.obs.bait} />}
      </div>
    </button>
  );
}

/* ---- chip-set helper for the form ---- */
function ChipSet({ options, value, onChange, multi = false }) {
  const isOn = (o) => multi ? (value || []).includes(o) : value === o;
  const toggle = (o) => {
    if (multi) { const set = new Set(value || []); set.has(o) ? set.delete(o) : set.add(o); onChange([...set]); }
    else onChange(o);
  };
  return (
    <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
      {options.map(o => (
        <button key={o} onClick={() => toggle(o)} style={{
          height: 40, padding: '0 14px', borderRadius: 'var(--r-pill)', cursor: 'pointer', fontSize: 14, fontWeight: 600,
          background: isOn(o) ? 'color-mix(in srgb, var(--keyline) 14%, var(--surface))' : 'var(--surface-raised)',
          color: isOn(o) ? 'var(--text)' : 'var(--text-dim)',
          border: `1.5px solid ${isOn(o) ? 'var(--keyline-soft)' : 'var(--border)'}`,
        }}>{o}</button>
      ))}
    </div>
  );
}
function FormField({ label, children }) {
  return (
    <div style={{ marginBottom: 20 }}>
      <div className="overline" style={{ marginBottom: 10 }}>{label}</div>
      {children}
    </div>
  );
}
function TextField({ value, placeholder, onChange, multi = false }) {
  return multi ? (
    <textarea value={value} placeholder={placeholder} onChange={e => onChange(e.target.value)} rows={3} style={{
      width: '100%', resize: 'none', background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-md)',
      padding: '12px 14px', color: 'var(--text)', fontFamily: 'var(--font-body)', fontSize: 15, lineHeight: 1.4,
    }} />
  ) : (
    <input value={value} placeholder={placeholder} onChange={e => onChange(e.target.value)} style={{
      width: '100%', height: 'var(--field-h)', background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-md)',
      padding: '0 14px', color: 'var(--text)', fontFamily: 'var(--font-body)', fontSize: 15,
    }} />
  );
}

/* Searchable spot picker for the log form. Type "New Harbour" and pick it
   directly - it sets both the exact mark AND its parent area. Marks lead the
   results (that's what people name); areas come after. */
function LocationPicker({ areaId, markId, onChange }) {
  const { useState } = React;
  const T = window.TURN;
  const [open, setOpen] = useState(false);
  const [q, setQ] = useState('');

  const areaObj = areaById(areaId);
  const markObj = markId && areaObj && (areaObj.marks || []).find(m => m.id === markId);
  const label = markObj ? markObj.name : (areaObj ? areaObj.name : 'Pick a spot');
  const sub = markObj ? `${markObj.type} · ${areaObj.name}`
    : (areaObj ? `${areaObj.distKm}km ${areaObj.bearing} · whole area` : '');

  const allMarks = T.areas.flatMap(a => (a.marks || []).map(m => ({ ...m, areaId: a.id, areaName: a.name })));
  const ql = q.trim().toLowerCase();
  const markHits = (ql ? allMarks.filter(m => m.name.toLowerCase().includes(ql) || (m.type || '').toLowerCase().includes(ql)) : allMarks);
  const areaHits = T.areas.filter(a => !a.gatedOut && (!ql || a.name.toLowerCase().includes(ql) || (a.sub || '').toLowerCase().includes(ql)));

  if (!open) {
    return (
      <button type="button" onClick={() => { setOpen(true); setQ(''); }} style={{ display: 'flex', alignItems: 'center', gap: 10, width: '100%', height: 'var(--field-h)', padding: '0 14px', background: 'var(--surface)', border: '1px solid var(--border-strong)', borderRadius: 'var(--r-md)', cursor: 'pointer', textAlign: 'left' }}>
        <Icon name="pin" size={16} color="var(--text-label)" />
        <span style={{ flex: 1, minWidth: 0 }}>
          <span style={{ display: 'block', color: 'var(--text)', fontSize: 16, fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{label}</span>
          {sub && <span style={{ display: 'block', fontSize: 11.5, color: 'var(--text-label)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{sub}</span>}
        </span>
        <Icon name="chevron" size={16} color="var(--text-label)" style={{ transform: 'rotate(90deg)' }} />
      </button>
    );
  }

  const Row = ({ kind, title, subtitle, onClick }) => (
    <button type="button" onClick={onClick} style={{ display: 'flex', alignItems: 'center', gap: 10, width: '100%', padding: '11px 12px', background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-sm)', cursor: 'pointer', textAlign: 'left' }}>
      <span style={{ flex: '0 0 auto', fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '.06em', textTransform: 'uppercase', color: 'var(--text-label)', border: '1px solid var(--border-strong)', borderRadius: 'var(--r-pill)', padding: '2px 6px' }}>{kind}</span>
      <span style={{ flex: 1, minWidth: 0 }}>
        <span style={{ display: 'block', fontWeight: 700, fontSize: 14.5, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{title}</span>
        {subtitle && <span style={{ display: 'block', fontSize: 11.5, color: 'var(--text-label)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{subtitle}</span>}
      </span>
    </button>
  );

  return (
    <div style={{ background: 'var(--surface)', border: '1px solid var(--border-strong)', borderRadius: 'var(--r-md)', padding: 8 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '0 6px 8px' }}>
        <Icon name="pin" size={15} color="var(--text-label)" />
        <input autoFocus value={q} onChange={e => setQ(e.target.value)} placeholder="Search New Harbour, Kwaaiwater, an area…" style={{ flex: 1, minWidth: 0, background: 'none', border: 'none', outline: 'none', color: 'var(--text)', fontFamily: 'var(--font-body)', fontSize: 15 }} />
        <button type="button" onClick={() => setOpen(false)} aria-label="close" style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--text-label)', display: 'grid', placeItems: 'center' }}><Icon name="close" size={15} /></button>
      </div>
      <div style={{ maxHeight: 260, overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 5 }}>
        {markHits.length > 0 && <div className="overline" style={{ fontSize: 9.5, padding: '4px 6px 0' }}>marks</div>}
        {markHits.map(m => (
          <Row key={m.id} kind="mark" title={m.name} subtitle={`${m.type} · ${m.areaName}`} onClick={() => { onChange(m.areaId, m.id); setOpen(false); }} />
        ))}
        {areaHits.length > 0 && <div className="overline" style={{ fontSize: 9.5, padding: '6px 6px 0' }}>areas (whole)</div>}
        {areaHits.map(a => (
          <Row key={a.id} kind="area" title={a.name} subtitle={`${a.distKm}km ${a.bearing}`} onClick={() => { onChange(a.id, null); setOpen(false); }} />
        ))}
        {markHits.length === 0 && areaHits.length === 0 && (
          <div style={{ padding: '16px 8px', color: 'var(--text-label)', fontSize: 13 }}>No match. Try a mark, area, or clear the search.</div>
        )}
      </div>
    </div>
  );
}

/* ---- new log form (full screen) ---- */
function LogForm({ areaId, onClose, onSaved }) {
  const { useState } = React;
  const T = window.TURN;
  const seed = areaById(areaId) || areaById(T.today.primary.areaId);
  const call = T.today.primary;
  const [area, setArea] = useState(seed.id);
  const [mark, setMark] = useState(null); // specific mark within the area (null = whole area)
  const [outcome, setOutcome] = useState('went');
  const [platform, setPlatform] = useState(call.platform.mode);
  const [method, setMethod] = useState(call.method.mode);
  const [mouth, setMouth] = useState('unknown');
  const [water, setWater] = useState('unknown');
  const [bait, setBait] = useState('unknown');
  const [tackle, setTackle] = useState('');
  const [result, setResult] = useState('');
  const [notes, setNotes] = useState('');
  const areaObj = areaById(area);

  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 50, background: 'var(--scrim)' }}>
      <div style={{ position: 'absolute', left: 0, right: 0, bottom: 0, top: 36, background: 'var(--bg)', borderTopLeftRadius: 'var(--r-xl)', borderTopRightRadius: 'var(--r-xl)', boxShadow: 'var(--shadow-sheet)', borderTop: '1px solid var(--hairline-bold)', display: 'flex', flexDirection: 'column' }}>
        {/* header */}
        <div style={{ padding: '12px var(--gutter) 12px', borderBottom: '1px solid var(--hairline)' }}>
          <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 10 }}><span style={{ width: 40, height: 4, borderRadius: 999, background: 'var(--border-strong)' }} /></div>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <h1 style={{ fontSize: 24, color: 'var(--text)' }}>New log</h1>
            <button onClick={onClose} style={{ background: 'var(--surface-raised)', border: '1px solid var(--border-strong)', borderRadius: '50%', width: 40, height: 40, display: 'grid', placeItems: 'center', cursor: 'pointer', color: 'var(--text)' }}><Icon name="close" size={18} /></button>
          </div>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-label)', marginTop: 4 }}>conditions &amp; recommendation frozen from today · auto-filled</div>
        </div>

        {/* body */}
        <div style={{ flex: 1, overflowY: 'auto', padding: '16px var(--gutter) 0' }}>
          <FormField label="Where">
            <LocationPicker
              areaId={area}
              markId={mark}
              onChange={(aid, mid) => { setArea(aid); setMark(mid); }}
            />
          </FormField>

          <FormField label="Outcome"><ChipSet options={['went', 'skipped', 'aborted']} value={outcome} onChange={setOutcome} /></FormField>

          {outcome !== 'skipped' && (
            <React.Fragment>
              <FormField label="Platform"><ChipSet options={['shore', 'kayak']} value={platform} onChange={setPlatform} /></FormField>
              <FormField label="Method"><ChipSet options={['fly', 'spin', 'bait']} value={method} onChange={setMethod} /></FormField>
            </React.Fragment>
          )}

          <FormField label="Mouth state"><ChipSet options={['open', 'partly-open', 'closed', 'unknown']} value={mouth} onChange={setMouth} /></FormField>
          <FormField label="Water clarity"><ChipSet options={['clean', 'green', 'off-colour', 'dirty', 'unknown']} value={water} onChange={setWater} /></FormField>
          <FormField label="Bait / birds"><ChipSet options={['baitfish-prominent', 'birds-working', 'some-signs', 'nothing-seen', 'unknown']} value={bait} onChange={setBait} /></FormField>

          {outcome === 'went' && (
            <React.Fragment>
              <FormField label="Tackle"><TextField value={tackle} placeholder="6wt floating, tan prawn" onChange={setTackle} /></FormField>
              <FormField label="Result"><TextField value={result} placeholder="2 grunter on prawn, lost a third" onChange={setResult} /></FormField>
            </React.Fragment>
          )}
          <FormField label="Notes (optional)"><TextField value={notes} placeholder="anything worth remembering next time…" onChange={setNotes} multi /></FormField>
          <div style={{ height: 8 }} />
        </div>

        {/* save / cancel */}
        <div style={{ display: 'flex', gap: 10, padding: '12px var(--gutter)', paddingBottom: 'calc(12px + var(--safe-bottom))', borderTop: '1px solid var(--hairline)', background: 'var(--bg)' }}>
          <LgButton variant="secondary" size="fat" onClick={onClose}>Cancel</LgButton>
          <LgButton variant="primary" size="fat" full onClick={async () => {
            // Persist through the engine if it exposed a saver. Falls back to
            // toast-only when running with demo data only.
            try {
              if (typeof window.__turnSaveLog === 'function') {
                await window.__turnSaveLog({
                  areaId: area,
                  markId: mark || undefined,
                  outcome,
                  platform: outcome === 'skipped' ? undefined : platform,
                  method:   outcome === 'skipped' ? undefined : method,
                  mouthState: mouth,
                  waterClarity: water,
                  baitPresence: bait,
                  tackle: tackle || undefined,
                  resultSummary: outcome === 'went' ? (result || undefined) : undefined,
                  notes: notes || undefined,
                });
              }
            } catch (err) {
              console.error('[turn] saveLog failed', err);
            }
            const markName = mark && (areaObj.marks || []).find(m => m.id === mark);
            onSaved(markName ? markName.name : areaObj.name, outcome);
          }}>Save log</LgButton>
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   Log screen
   ============================================================ */
function LogScreen({ onLog, onArea, onNewLog }) {
  const { useState } = React;
  const T = window.TURN;
  const [filter, setFilter] = useState('all');
  const logs = filter === 'all' ? T.logs : T.logs.filter(l => l.outcome === filter);

  return (
    <div style={{ padding: '4px var(--gutter) 0', display: 'flex', flexDirection: 'column', gap: 14 }}>
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between' }}>
        <div>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 22, color: 'var(--text)', letterSpacing: '-0.02em' }}>Log</div>
          <div className="overline" style={{ marginTop: 2 }}>every session you've banked</div>
        </div>
      </div>

      <LgButton variant="primary" size="fat" full onClick={() => onNewLog(null)} icon={<Icon name="plus" size={20} />}>New log</LgButton>

      {/* stats strip */}
      <div style={{ display: 'flex', background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-md)', overflow: 'hidden' }}>
        {[{ k: 'tripsThisMonth', l: 'trips · month' }, { k: 'areasVisited', l: 'spots worked' }, { k: 'catchesRecorded', l: 'fish banked' }].map((s, i) => (
          <div key={s.k} style={{ flex: 1, padding: '12px 14px', borderLeft: i ? '1px solid var(--hairline)' : 'none' }}>
            <div className="metric" style={{ fontSize: 26, fontWeight: 700, color: 'var(--text)', lineHeight: 1 }}>{T.stats[s.k]}</div>
            <div className="overline" style={{ fontSize: 10, marginTop: 5 }}>{s.l}</div>
          </div>
        ))}
      </div>

      {/* nudges */}
      {T.nudges.length > 0 && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {T.nudges.map((n, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '12px 14px', background: 'color-mix(in srgb, var(--verdict-caution) 9%, var(--surface))', border: '1px solid color-mix(in srgb, var(--verdict-caution) 35%, var(--border))', borderRadius: 'var(--r-md)' }}>
              <Icon name="clock" size={16} color="var(--verdict-caution)" />
              <span style={{ fontSize: 13.5, color: 'var(--text)', lineHeight: 1.3 }}>{n}</span>
            </div>
          ))}
        </div>
      )}

      <SectionLabel right={<FilterRow value={filter} onChange={setFilter} options={[{ value: 'all', label: 'all' }, { value: 'went', label: 'went' }, { value: 'skipped', label: 'skipped' }, { value: 'aborted', label: 'aborted' }]} />}>the logbook</SectionLabel>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {logs.map(l => <LogRow key={l.id} log={l} onLog={onLog} onArea={onArea} />)}
        {logs.length === 0 && (
          <div style={{ padding: '28px 20px', textAlign: 'center', color: 'var(--text-label)', fontSize: 14, border: '1px dashed var(--border-strong)', borderRadius: 'var(--r-md)' }}>
            no trips like that on record - bit of a drought
          </div>
        )}
      </div>
      <div style={{ height: 8 }} />
    </div>
  );
}

Object.assign(window, { LogScreen, LogForm, OUTCOME });
