// iceland-panels.jsx — info panels. Needs GL, Ph, TopBar, CheckRow, useStored, MAP, window.TRIP
const { useState: useStateP } = React;

function RouteMap({ activeDay, onPick }) {
  const legPts = activeDay == null ? null : TRIP.legs[activeDay].map(id => MAP.byId[id]);
  const allLegs = TRIP.legs.map(leg => leg.map(id => MAP.byId[id]));
  const toPath = pts => pts.map((p, i) => `${i ? 'L' : 'M'}${p.x} ${p.y}`).join(' ');
  return (
    <div style={{ position: 'relative', width: '100%', paddingBottom: `${100 / MAP.aspect}%`,
      borderRadius: 16, overflow: 'hidden', border: `1px solid ${GL.line}`,
      background: 'radial-gradient(120% 120% at 30% 10%, oklch(0.26 0.04 232), oklch(0.15 0.03 240) 70%)' }}>
      {/* faint grid */}
      <div style={{ position: 'absolute', inset: 0, backgroundImage:
        `linear-gradient(rgba(255,255,255,0.05) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,0.05) 1px, transparent 1px)`,
        backgroundSize: '14% 18%' }} />
      <svg viewBox="0 0 100 100" preserveAspectRatio="none" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }}>
        {/* all legs faint */}
        {allLegs.map((pts, i) => (
          <path key={i} d={toPath(pts)} fill="none" stroke="rgba(255,255,255,0.13)" strokeWidth="0.5"
            vectorEffect="non-scaling-stroke" strokeDasharray="2 2" />
        ))}
        {/* active leg */}
        {legPts && <path d={toPath(legPts)} fill="none" stroke={GL.glacier} strokeWidth="1.4"
          vectorEffect="non-scaling-stroke" strokeLinecap="round" strokeLinejoin="round" />}
      </svg>
      {/* pins */}
      {MAP.pts.map(p => {
        const on = legPts && TRIP.legs[activeDay].includes(p.id);
        return (
          <div key={p.id} style={{ position: 'absolute', left: `${p.x}%`, top: `${p.y}%`, transform: 'translate(-50%,-50%)', zIndex: on ? 3 : 2 }}>
            <div style={{ width: on ? 11 : 7, height: on ? 11 : 7, borderRadius: '50%',
              background: on ? GL.glacier : 'rgba(255,255,255,0.45)',
              boxShadow: on ? `0 0 0 4px ${GL.glacierDim}` : 'none', transition: 'all .2s' }} />
            <div style={{ position: 'absolute', left: '50%', top: on ? 14 : 10, transform: 'translateX(-50%)', whiteSpace: 'nowrap',
              fontFamily: GL.mono, fontSize: 8.5, letterSpacing: 0.2,
              color: on ? GL.glacier : 'rgba(255,255,255,0.5)', fontWeight: on ? 700 : 400 }}>{p.name}</div>
          </div>
        );
      })}
    </div>
  );
}

function MapsButton({ url, label }) {
  return (
    <a href={url} target="_blank" rel="noopener" style={{
      display: 'flex', alignItems: 'center', gap: 11, textDecoration: 'none',
      padding: '13px 15px', borderRadius: 13, background: GL.surface, border: `1px solid ${GL.line}`,
    }}>
      <div style={{ width: 34, height: 34, borderRadius: 9, flexShrink: 0, background: GL.glacierDim,
        display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M12 21s7-6.3 7-11a7 7 0 10-14 0c0 4.7 7 11 7 11z" stroke={GL.glacier} strokeWidth="2" strokeLinejoin="round"/><circle cx="12" cy="10" r="2.4" fill={GL.glacier}/></svg>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontFamily: GL.mono, fontSize: 9, letterSpacing: 1, color: GL.faint }}>OPEN IN GOOGLE MAPS</div>
        <div style={{ fontFamily: GL.body, fontWeight: 600, fontSize: 13.5, color: GL.text, lineHeight: 1.25, marginTop: 2 }}>{label}</div>
      </div>
      <svg width="15" height="15" viewBox="0 0 24 24" fill="none" style={{ flexShrink: 0 }}><path d="M7 17L17 7M9 7h8v8" stroke={GL.mut} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
    </a>
  );
}

// ── Panel scaffold ───────────────────────────────────────────
function Panel({ title, onBack, lede, children }) {
  return (
    <div style={{ height: '100%', overflowY: 'auto', WebkitOverflowScrolling: 'touch', background: GL.bg }}>
      <TopBar title={title} onBack={onBack} />
      <div style={{ padding: '18px 18px 60px' }}>
        {lede && <p style={{ fontFamily: GL.body, fontSize: 14.5, lineHeight: 1.5, color: GL.mut, margin: '0 0 20px' }}>{lede}</p>}
        {children}
      </div>
    </div>
  );
}

// ── Routes ───────────────────────────────────────────────────
function RoutesPanel({ onBack }) {
  const [day, setDay] = useStateP(1);
  return (
    <Panel title="Routes" onBack={onBack} lede="Tik een dag om de route op de kaart te zien — open ’m daarna in Google Maps voor turn-by-turn navigatie.">
      <DayRouteMap day={day} />
      <div style={{ display: 'flex', gap: 7, marginTop: 16, flexWrap: 'wrap' }}>
        {TRIP.days.map((d, i) => (
          <button key={d.n} onClick={() => setDay(i)} style={{
            fontFamily: GL.mono, fontSize: 11, letterSpacing: 0.5, padding: '8px 12px', borderRadius: 9, cursor: 'pointer',
            background: day === i ? GL.glacier : GL.surface, color: day === i ? GL.bg : GL.mut,
            border: `1px solid ${day === i ? GL.glacier : GL.line}`, fontWeight: day === i ? 700 : 400,
          }}>{d.dow} {d.date.split(' ')[0]}</button>
        ))}
      </div>
      <div style={{ marginTop: 22, display: 'flex', flexDirection: 'column', gap: 10 }}>
        <div style={{ fontFamily: GL.mono, fontSize: 10, letterSpacing: 1.5, color: GL.faint, marginBottom: 2 }}>
          DAG {TRIP.days[day].n} · {TRIP.days[day].title.toUpperCase()}
        </div>
        <MapsButton url={TRIP.days[day].route.url} label={TRIP.days[day].route.label} />
      </div>
      <div style={{ marginTop: 26 }}>
        <div style={{ fontFamily: GL.mono, fontSize: 10, letterSpacing: 1.5, color: GL.faint, marginBottom: 12 }}>ALLE ROUTES</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
          {TRIP.days.map(d => <MapsButton key={d.n} url={d.route.url} label={`${d.dow} ${d.date} — ${d.route.label}`} />)}
        </div>
      </div>
    </Panel>
  );
}

// ── Paklijst ─────────────────────────────────────────────────
function PaklijstPanel({ onBack }) {
  const [done, setDone] = useStored('ijsland_paklijst', {});
  const count = TRIP.packing.filter(p => done[p.id]).length;
  return (
    <Panel title="Paklijst" onBack={onBack} lede="September in IJsland: 5–12 °C, wind en snel wisselend weer. Vink af wat in de tas zit.">
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
        <div style={{ flex: 1, height: 6, borderRadius: 3, background: GL.surface, overflow: 'hidden' }}>
          <div style={{ width: `${(count / TRIP.packing.length) * 100}%`, height: '100%', background: GL.glacier, transition: 'width .25s' }} />
        </div>
        <div style={{ fontFamily: GL.mono, fontSize: 11, color: GL.mut }}>{count}/{TRIP.packing.length}</div>
      </div>
      <div style={{ background: GL.surface, border: `1px solid ${GL.line}`, borderRadius: 16, padding: '2px 14px' }}>
        {TRIP.packing.map((p, i) => (
          <CheckRow key={p.id} checked={!!done[p.id]} onToggle={() => setDone({ ...done, [p.id]: !done[p.id] })}
            text={p.text} note={p.note} last={i === TRIP.packing.length - 1} />
        ))}
      </div>
    </Panel>
  );
}

// ── Boekingen — alleen-lezen status (geregeld + nog te doen) ──
function ResRow({ k, v }) {
  return (
    <div style={{ display: 'flex', gap: 10, padding: '5px 0' }}>
      <div style={{ flexShrink: 0, width: 76, fontFamily: GL.mono, fontSize: 10, letterSpacing: 0.4, color: GL.faint, paddingTop: 1 }}>{k}</div>
      <div style={{ flex: 1, fontFamily: GL.body, fontSize: 13, color: GL.text, lineHeight: 1.4 }}>{v}</div>
    </div>
  );
}

function DoneCard({ item, last }) {
  return (
    <div style={{ background: GL.surface, border: `1px solid ${GL.line}`, borderRadius: 15, padding: '15px 16px', marginBottom: last ? 0 : 11 }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 11 }}>
        <div style={{ width: 22, height: 22, borderRadius: '50%', flexShrink: 0, marginTop: 1, background: GL.glacier,
          display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <svg width="12" height="12" viewBox="0 0 13 13" fill="none"><path d="M2 7l3 3 6-7" stroke={GL.bg} strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/></svg>
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 8 }}>
            <span style={{ fontFamily: GL.mono, fontSize: 9.5, letterSpacing: 1, color: GL.glacier }}>{item.tag}</span>
            {item.ref && <span style={{ fontFamily: GL.mono, fontSize: 9.5, color: GL.faint, whiteSpace: 'nowrap' }}>REF {item.ref}</span>}
          </div>
          <div style={{ fontFamily: GL.body, fontWeight: 700, fontSize: 15.5, color: GL.text, lineHeight: 1.25, marginTop: 4 }}>{item.title}</div>
          {item.sub && <div style={{ fontFamily: GL.body, fontSize: 12.5, color: GL.mut, marginTop: 3, lineHeight: 1.35 }}>{item.sub}</div>}
          {item.rows && (
            <div style={{ marginTop: 9, borderTop: `1px solid ${GL.line}`, paddingTop: 6 }}>
              {item.rows.map((r, i) => <ResRow key={i} k={r[0]} v={r[1]} />)}
            </div>
          )}
          {item.note && <div style={{ fontFamily: GL.body, fontSize: 12, color: GL.faint, marginTop: 9, lineHeight: 1.45 }}>{item.note}</div>}
          {(item.map || item.src) && (
            <div style={{ display: 'flex', gap: 18, marginTop: 12 }}>
              {item.map && <PinLink href={item.map} kind="map">Kaart</PinLink>}
              {item.src && <PinLink href={item.src.url} kind="ext">{item.src.label}</PinLink>}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function TodoCard({ item, last }) {
  return (
    <div style={{ background: 'transparent', border: `1px dashed ${GL.lineStrong}`, borderRadius: 15, padding: '14px 16px', marginBottom: last ? 0 : 11 }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 11 }}>
        <div style={{ width: 22, height: 22, borderRadius: '50%', flexShrink: 0, marginTop: 1, border: `1.5px solid ${GL.warn}` }} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 8 }}>
            <span style={{ fontFamily: GL.mono, fontSize: 9.5, letterSpacing: 1, color: GL.warn }}>{item.tag}</span>
            <span style={{ fontFamily: GL.mono, fontSize: 9, letterSpacing: 0.5, color: GL.warn, whiteSpace: 'nowrap' }}>TE BOEKEN</span>
          </div>
          <div style={{ fontFamily: GL.body, fontWeight: 700, fontSize: 15.5, color: GL.text, lineHeight: 1.25, marginTop: 4 }}>{item.title}</div>
          {item.sub && <div style={{ fontFamily: GL.body, fontSize: 12.5, color: GL.mut, marginTop: 3, lineHeight: 1.35 }}>{item.sub}</div>}
          {item.note && <div style={{ fontFamily: GL.body, fontSize: 12, color: GL.faint, marginTop: 8, lineHeight: 1.45 }}>{item.note}</div>}
          {item.map && <div style={{ marginTop: 11 }}><PinLink href={item.map} kind="map">Kaart</PinLink></div>}
        </div>
      </div>
    </div>
  );
}

function BoekingenPanel({ onBack }) {
  const r = TRIP.reservations;
  return (
    <Panel title="Boekingen" onBack={onBack}
      lede="Overzicht van wat al vastligt — met alle details — en wat we nog moeten regelen. Alleen-lezen.">
      <div style={{ display: 'flex', gap: 10, marginBottom: 22 }}>
        <div style={{ flex: 1, background: GL.glacierDim, border: `1px solid ${GL.line}`, borderRadius: 13, padding: '13px 14px' }}>
          <div style={{ fontFamily: GL.display, fontSize: 30, color: GL.glacier, lineHeight: 1 }}>{r.done.length}</div>
          <div style={{ fontFamily: GL.mono, fontSize: 9.5, letterSpacing: 1, color: GL.mut, marginTop: 4 }}>GEREGELD</div>
        </div>
        <div style={{ flex: 1, background: GL.surface, border: `1px solid ${GL.line}`, borderRadius: 13, padding: '13px 14px' }}>
          <div style={{ fontFamily: GL.display, fontSize: 30, color: GL.warn, lineHeight: 1 }}>{r.todo.length}</div>
          <div style={{ fontFamily: GL.mono, fontSize: 9.5, letterSpacing: 1, color: GL.mut, marginTop: 4 }}>NOG TE DOEN</div>
        </div>
      </div>

      {r.todo.length > 0 ? (
        <React.Fragment>
          <div style={{ fontFamily: GL.mono, fontSize: 10, letterSpacing: 1.5, color: GL.warn, marginBottom: 12 }}>● NOG TE REGELEN</div>
          {r.todo.map((item, i) => <TodoCard key={item.id} item={item} last={i === r.todo.length - 1} />)}
        </React.Fragment>
      ) : (
        <div style={{ fontFamily: GL.mono, fontSize: 11.5, letterSpacing: 0.5, color: GL.glacier, background: GL.glacierDim,
          border: `1px solid ${GL.line}`, borderRadius: 12, padding: '15px', textAlign: 'center' }}>Alles is geboekt — niks meer te regelen. Skál!</div>
      )}

      <div style={{ fontFamily: GL.mono, fontSize: 10, letterSpacing: 1.5, color: GL.glacier, margin: '26px 0 12px' }}>✓ GEREGELD</div>
      {r.done.map((item, i) => <DoneCard key={item.id} item={item} last={i === r.done.length - 1} />)}
    </Panel>
  );
}

// ── Slaapplekken ─────────────────────────────────────────────
function SlaapPanel({ onBack }) {
  return (
    <Panel title="Slaapplekken" onBack={onBack} lede="Een slimme lus: zo min mogelijk koffers slepen, twee nachten in de blokhut met hottub als uitvalsbasis, laatste avond in Reykjavík zonder BOB.">
      <div style={{ display: 'flex', flexDirection: 'column', gap: 11 }}>
        {TRIP.sleep.map((s, i) => (
          <div key={i} style={{ background: GL.surface, border: `1px solid ${GL.line}`, borderRadius: 14, padding: '15px 16px' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
              <div style={{ fontFamily: GL.display, fontSize: 19, textTransform: 'uppercase', color: GL.text }}>{s.base}</div>
              <div style={{ fontFamily: GL.mono, fontSize: 11, letterSpacing: 1, color: GL.glacier }}>{s.night}</div>
            </div>
            <div style={{ fontFamily: GL.body, fontSize: 13, color: GL.mut, marginTop: 5, lineHeight: 1.4 }}>{s.why}</div>
          </div>
        ))}
      </div>
    </Panel>
  );
}

// ── Praktisch (daglicht + zelf rijden) ───────────────────────
function PraktischPanel({ onBack }) {
  return (
    <Panel title="Praktisch" onBack={onBack}>
      <div style={{ borderRadius: 16, overflow: 'hidden', border: `1px solid ${GL.line}`, marginBottom: 18 }}>
        <Ph label="Noorderlicht boven de blokhut" hue={262} h={130} src={TRIP.meta.auroraImg} />
        <div style={{ padding: '15px 16px', background: GL.surface }}>
          <div style={{ fontFamily: GL.display, fontSize: 18, textTransform: 'uppercase', color: GL.text }}>Daglicht & noorderlicht</div>
          <div style={{ fontFamily: GL.body, fontSize: 13.5, color: GL.mut, marginTop: 6, lineHeight: 1.5 }}>{TRIP.meta.daylight}</div>
        </div>
      </div>
      <div style={{ background: GL.surface, border: `1px solid ${GL.line}`, borderRadius: 16, padding: '16px 17px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginBottom: 8 }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M3 13l2-5h11l3 5M5 13h15v4H4v-4z" stroke={GL.glacier} strokeWidth="1.8" strokeLinejoin="round"/><circle cx="7.5" cy="17.5" r="1.6" fill={GL.glacier}/><circle cx="16.5" cy="17.5" r="1.6" fill={GL.glacier}/></svg>
          <div style={{ fontFamily: GL.display, fontSize: 18, textTransform: 'uppercase', color: GL.text }}>Zelf rijden</div>
        </div>
        <div style={{ fontFamily: GL.body, fontSize: 13.5, color: GL.mut, lineHeight: 1.55 }}>{TRIP.driving}</div>
      </div>
      <div style={{ marginTop: 16, display: 'flex', gap: 10 }}>
        {[['Vlucht heen', 'HV6885 · do 18:15'], ['Vlucht terug', 'HV6888 · ma 08:50']].map(([k, v]) => (
          <div key={k} style={{ flex: 1, background: GL.surface, border: `1px solid ${GL.line}`, borderRadius: 13, padding: '13px 14px' }}>
            <div style={{ fontFamily: GL.mono, fontSize: 9.5, letterSpacing: 1, color: GL.faint }}>{k.toUpperCase()}</div>
            <div style={{ fontFamily: GL.body, fontWeight: 700, fontSize: 14.5, color: GL.text, marginTop: 4 }}>{v}</div>
          </div>
        ))}
      </div>
      <div style={{ marginTop: 22, paddingTop: 16, borderTop: `1px solid ${GL.line}` }}>
        <div style={{ fontFamily: GL.mono, fontSize: 9.5, letterSpacing: 1.5, color: GL.faint, marginBottom: 8 }}>FOTO'S</div>
        {TRIP.credits.map((c, i) => (
          <div key={i} style={{ fontFamily: GL.body, fontSize: 11.5, color: GL.mut, lineHeight: 1.45, marginBottom: 4 }}>
            {c.what} — {c.who} · {c.lic}
          </div>
        ))}
        <div style={{ fontFamily: GL.body, fontSize: 11.5, color: GL.faint, lineHeight: 1.45, marginTop: 4 }}>Kaart © OpenStreetMap, © CARTO. Overige foto's: eigen materiaal.</div>
      </div>
    </Panel>
  );
}

// ── Budget ───────────────────────────────────────────────────
function BudgetPanel({ onBack }) {
  const b = TRIP.budget;
  return (
    <Panel title="Budget" onBack={onBack} lede={b.note}>
      <div style={{ background: GL.surface, border: `1px solid ${GL.line}`, borderRadius: 16, overflow: 'hidden' }}>
        {b.rows.map((r, i) => (
          <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '14px 16px', borderBottom: `1px solid ${GL.line}` }}>
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: GL.body, fontWeight: 600, fontSize: 14.5, color: GL.text }}>{r.post}</div>
              <div style={{ fontFamily: GL.body, fontSize: 12, color: GL.faint, marginTop: 2 }}>{r.note}</div>
            </div>
            <div style={{ fontFamily: GL.mono, fontSize: 15, color: GL.text }}>~€{r.pp}</div>
          </div>
        ))}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '16px 16px' }}>
          <div style={{ fontFamily: GL.display, fontSize: 18, textTransform: 'uppercase', color: GL.text }}>Totaal p.p.</div>
          <div style={{ fontFamily: GL.display, fontSize: 26, color: GL.glacier }}>~€{b.total.toLocaleString('nl-NL')}</div>
        </div>
      </div>
      <p style={{ fontFamily: GL.body, fontSize: 12.5, color: GL.faint, lineHeight: 1.5, marginTop: 16 }}>
        Niet meegerekend: brandstof voor de huurbus en eten &amp; drinken (diners ~€35–60, bier ~€11). Kraanwater is gratis en perfect.
      </p>
    </Panel>
  );
}

Object.assign(window, { RoutesPanel, PaklijstPanel, BoekingenPanel, SlaapPanel, PraktischPanel, BudgetPanel, MapsButton, RouteMap });
