/* Day Trip Planner — screens B: Itinerary · Stop detail · Reroll */
const { Icon: I2, StatusBar: SB2, MapPreview, Placeholder: PH2,
        Tag: Tag2, Stat, Button: Btn2, IconButton: IB2 } = window;

// drive-time connector between two stops
function DriveConnector({ min }) {
  const miles = (min * 0.62).toFixed(1);
  return (
    <div className="drive" style={{ paddingLeft: 36 }}>
      <span style={{ width: 2, height: 14, borderLeft: '2px dashed var(--line)', marginLeft: 13 }} />
      <span className="row gap8" style={{ marginLeft: 8 }}>
        <I2 name="car" size={15} /> {min} min drive
        <span className="faint" style={{ fontWeight: 600 }}>&middot; {miles} mi</span>
      </span>
    </div>
  );
}

function StopRow({ num, stop, onOpen }) {
  return (
    <div className="stop card" onClick={onOpen}
      style={{ padding: 12, alignItems: 'stretch', gap: 13, boxShadow: 'var(--shadow-sm), inset 0 0 0 1px var(--line-2)' }}>
      <div style={{ position: 'relative', flex: '0 0 auto' }}>
        <PH2 tone={stop.tone} src={window.stopPhoto(stop, 200, 200)} label={stop.cat.toLowerCase().split('/')[0]}
          style={{ width: 78, height: 78, borderRadius: 'calc(var(--r) * 0.7)' }}
          labelStyle={{ fontSize: 8.5, padding: '2px 6px' }} />
        <span className="stop-num" style={{ position: 'absolute', top: -8, left: -8, width: 26, height: 26 }}>{num}</span>
      </div>
      <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
        <div className="row gap8" style={{ marginBottom: 5 }}>
          <Tag2 tone={stop.tone}>{stop.cat.split('/')[0]}</Tag2>
          <span className="faint" style={{ fontSize: 12, fontWeight: 600 }}>{stop.area}</span>
        </div>
        <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 16.5,
          letterSpacing: '-0.01em', lineHeight: 1.12, marginBottom: 3 }}>{stop.name}</div>
        <div className="muted" style={{ fontSize: 13, lineHeight: 1.34 }}>{stop.why}</div>
      </div>
      <span style={{ color: 'var(--ink-3)', alignSelf: 'center', flex: '0 0 auto' }}><I2 name="chevR" size={18} /></span>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 4 · Itinerary result
// ─────────────────────────────────────────────────────────────
function ItineraryScreen({ stops, totals, location, hours, onOpenStop, onReroll, onSave, saved }) {
  return (
    <div className="screen scr-enter" style={{ background: 'var(--sand)' }}>
      <SB2 theme="dark" floating />
      <div className="screen-body">
        {/* map */}
        <div style={{ position: 'relative' }}>
          <MapPreview height={206} />
          <div style={{ position: 'absolute', top: 56, right: 16, display: 'flex', gap: 9 }}>
            <IB2 name="map" label="Expand map" />
          </div>
          <div style={{ position: 'absolute', left: 16, bottom: 26 }}>
            <span className="tag" style={{ background: 'rgba(255,255,255,0.9)', color: 'var(--ink)',
              backdropFilter: 'blur(4px)', boxShadow: 'var(--shadow-sm)' }}>
              <I2 name="car" size={14} /> {totals.drivingLabel} driving · {stops.length} stops
            </span>
          </div>
        </div>

        {/* card */}
        <div style={{ background: 'var(--sand)', borderRadius: '26px 26px 0 0', marginTop: -22,
          position: 'relative', padding: '22px 22px 0' }}>
          <div className="row gap8" style={{ marginBottom: 8 }}>
            <Tag2 tone="sage"><I2 name="check" size={13} /> Your plan's ready</Tag2>
          </div>
          <h2 style={{ fontSize: 26, lineHeight: 1.08 }}>
            You've got {hours} hours.<br/>Here's where to go.
          </h2>
          <p className="muted" style={{ fontSize: 14, marginTop: 8 }}>
            <I2 name="pin" size={13} style={{ verticalAlign: '-2px' }} /> Starting from {location}
          </p>

          {/* stat row */}
          <div className="card" style={{ display: 'flex', justifyContent: 'space-between',
            padding: '16px 20px', marginTop: 16 }}>
            <Stat k="Time">{totals.timeLabel}</Stat>
            <span style={{ width: 1, background: 'var(--line)' }} />
            <Stat k="Driving">{totals.drivingShort}</Stat>
            <span style={{ width: 1, background: 'var(--line)' }} />
            <Stat k="Est. cost">{totals.costLabel}</Stat>
          </div>

          {/* stops */}
          <div className="field-label" style={{ margin: '24px 4px 12px' }}>The day, in order</div>
          <div>
            {stops.map((s, i) => (
              <React.Fragment key={s.id}>
                {i > 0 && <DriveConnector min={s.drive} />}
                <StopRow num={i + 1} stop={s} onOpen={() => onOpenStop(s.id)} />
              </React.Fragment>
            ))}
          </div>
          <p className="faint" style={{ textAlign: 'center', fontSize: 12.5, margin: '18px 0 6px' }}>
            Costs are rough estimates for two. Hours change — tap a stop to check.
          </p>
        </div>
      </div>

      {/* actions */}
      <div style={{ flex: '0 0 auto', display: 'flex', gap: 11, padding: '12px 22px 30px',
        background: 'linear-gradient(180deg, rgba(244,236,221,0), var(--sand) 36%)' }}>
        <Btn2 variant="secondary" icon={saved ? 'check' : 'heart'} onClick={onSave}
          style={{ flex: '0 0 42%' }}>{saved ? 'Saved' : 'Save'}</Btn2>
        <Btn2 variant="primary" icon="reroll" onClick={onReroll} style={{ flex: 1 }}>Reroll the day</Btn2>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 5 · Individual stop detail
// ─────────────────────────────────────────────────────────────
function StopDetailScreen({ stop, num, total, onBack, onSwap, onRemove, onMaps }) {
  return (
    <div className="screen scr-enter" style={{ background: 'var(--sand)' }}>
      <SB2 theme="light" floating />
      <div className="screen-body">
        {/* hero */}
        <div style={{ position: 'relative' }}>
          <PH2 tone={stop.tone} src={window.stopPhoto(stop, 800, 640)} label={`photo · ${stop.name.toLowerCase()}`}
            style={{ height: 312, borderRadius: 0 }} labelStyle={{ fontSize: 11 }} />
          <div style={{ position: 'absolute', inset: 0, background:
            'linear-gradient(180deg, rgba(43,38,32,0.28) 0%, rgba(43,38,32,0) 30%, rgba(43,38,32,0) 62%, rgba(43,38,32,0.30) 100%)' }} />
          <div style={{ position: 'absolute', top: 52, left: 16, right: 16, display: 'flex', justifyContent: 'space-between' }}>
            <IB2 name="chevL" label="Back" onClick={onBack}
              style={{ background: 'rgba(255,255,255,0.92)', backdropFilter: 'blur(6px)' }} />
            <IB2 name="heart" label="Save stop"
              style={{ background: 'rgba(255,255,255,0.92)', backdropFilter: 'blur(6px)' }} />
          </div>
          <div style={{ position: 'absolute', left: 18, bottom: 16, display: 'flex', alignItems: 'center', gap: 10 }}>
            <span className="stop-num" style={{ width: 30, height: 30, fontSize: 14 }}>{num}</span>
            <span style={{ color: '#fff', fontWeight: 700, fontSize: 13, letterSpacing: '0.01em',
              textShadow: '0 1px 6px rgba(0,0,0,0.4)' }}>Stop {num} of {total}</span>
          </div>
        </div>

        <div className="screen-pad" style={{ paddingTop: 18 }}>
          <div className="row gap8" style={{ marginBottom: 9 }}>
            <Tag2 tone={stop.tone}>{stop.cat.split('/')[0]}</Tag2>
            <Tag2><I2 name="pin" size={12} /> {stop.area}</Tag2>
          </div>
          <h2 style={{ fontSize: 27, lineHeight: 1.08 }}>{stop.name}</h2>

          {/* drive-from-prev */}
          {num > 1 && (
            <div className="row gap8" style={{ marginTop: 14, color: 'var(--accent)', fontWeight: 700, fontSize: 14 }}>
              <I2 name="car" size={16} /> {stop.drive} min drive from your last stop
            </div>
          )}

          {/* info rows */}
          <div className="card" style={{ marginTop: 16, padding: '4px 18px' }}>
            <div className="row gap12" style={{ padding: '14px 0', borderBottom: '1px solid var(--line)' }}>
              <I2 name="clock" size={19} style={{ color: 'var(--ink-2)', flex: '0 0 auto' }} />
              <div style={{ flex: 1 }}><div style={{ fontWeight: 600, fontSize: 14.5 }}>Open today</div>
                <div className="muted" style={{ fontSize: 13.5 }}>{stop.hours}</div></div>
              <span className="tag tag-sage" style={{ fontSize: 11 }}>Open now</span>
            </div>
            <div className="row gap12" style={{ padding: '14px 0' }}>
              <I2 name="pin" size={19} style={{ color: 'var(--ink-2)', flex: '0 0 auto' }} />
              <div style={{ flex: 1 }}><div style={{ fontWeight: 600, fontSize: 14.5 }}>Address</div>
                <div className="muted" style={{ fontSize: 13.5 }}>{stop.addr}</div></div>
              <span style={{ color: 'var(--ink-3)' }}><I2 name="chevR" size={16} /></span>
            </div>
          </div>

          {/* why picked */}
          <div className="field-label" style={{ margin: '22px 4px 8px' }}>
            <I2 name="sparkle" size={12} style={{ verticalAlign: '-1px', color: 'var(--accent)' }} /> Why we picked it
          </div>
          <p style={{ fontSize: 15.5, lineHeight: 1.6, color: 'var(--ink)', margin: 0 }}>{stop.long}</p>
          <div style={{ height: 14 }} />
        </div>
      </div>

      {/* action bar */}
      <div style={{ flex: '0 0 auto', display: 'flex', gap: 9, padding: '12px 18px 30px',
        background: 'linear-gradient(180deg, rgba(244,236,221,0), var(--sand) 34%)' }}>
        <Btn2 variant="secondary" size="sm" icon="swap" onClick={onSwap} style={{ flex: 1 }}>Swap stop</Btn2>
        <Btn2 variant="primary" size="sm" icon="open" onClick={onMaps} style={{ flex: 1 }}>Open in Maps</Btn2>
        <IB2 name="trash" label="Remove stop" onClick={onRemove}
          style={{ width: 44, height: 44, color: 'var(--coral-press)' }} />
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// 6 · Reroll / refine
// ─────────────────────────────────────────────────────────────
function RerollScreen({ stops, keeps, onToggle, onAdjust, onRegenerate }) {
  const keptCount = keeps.filter(Boolean).length;
  const replacing = stops.length - keptCount;
  return (
    <div className="screen scr-enter" style={{ background: 'var(--sand)' }}>
      <SB2 theme="dark" />
      <div className="scr-head" style={{ paddingTop: 6 }}>
        <IB2 name="chevL" label="Back" onClick={onAdjust} style={{ boxShadow: 'var(--shadow-sm), inset 0 0 0 1px var(--line-2)' }} />
        <div style={{ flex: 1 }}>
          <div className="scr-title" style={{ fontSize: 22 }}>Reroll the day</div>
          <div className="scr-sub">Keep what you like. We'll redo the rest.</div>
        </div>
      </div>

      <div className="screen-body screen-pad" style={{ paddingBottom: 8 }}>
        <div className="card" style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 18px', marginBottom: 18 }}>
          <span style={{ width: 38, height: 38, borderRadius: 11, background: 'var(--sage-soft)', color: 'var(--sage)',
            display: 'flex', alignItems: 'center', justifyContent: 'center', flex: '0 0 auto' }}>
            <I2 name="check" size={20} /></span>
          <div style={{ flex: 1, fontSize: 14, lineHeight: 1.4 }}>
            Keeping <b>{keptCount}</b> {keptCount === 1 ? 'stop' : 'stops'}.
            {replacing > 0 ? <> We'll swap the other <b>{replacing}</b>.</> : <> Toggle one to replace.</>}
          </div>
        </div>

        {stops.map((s, i) => {
          const kept = keeps[i];
          return (
            <div key={s.id} className="card" style={{ padding: 12, marginBottom: 12, display: 'flex', gap: 11,
              alignItems: 'center', opacity: kept ? 1 : 0.62, transition: 'opacity .2s',
              boxShadow: 'var(--shadow-sm), inset 0 0 0 1px ' + (kept ? 'color-mix(in oklab, var(--sage) 40%, transparent)' : 'var(--line-2)') }}>
              <div style={{ position: 'relative', flex: '0 0 auto' }}>
                <PH2 tone={s.tone} src={window.stopPhoto(s, 140, 140)} style={{ width: 52, height: 52, borderRadius: 'calc(var(--r) * 0.55)' }} />
                <span className="stop-num" style={{ position: 'absolute', top: -7, left: -7, width: 22, height: 22, fontSize: 11.5 }}>{i + 1}</span>
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 14.5,
                  lineHeight: 1.16, marginBottom: 5 }}>{s.name}</div>
                <div className="row gap8">
                  <Tag2 tone={s.tone}>{s.cat.split('/')[0]}</Tag2>
                </div>
              </div>
              <div className="seg" style={{ flex: '0 0 auto' }}>
                <div className="seg-thumb" style={{ left: kept ? 3 : '50%', width: 'calc(50% - 3px)',
                  background: kept ? 'var(--sage)' : 'var(--coral)' }} />
                <button data-on={kept ? '1' : '0'} onClick={() => onToggle(i, true)}>Keep</button>
                <button data-on={!kept ? '1' : '0'} onClick={() => onToggle(i, false)}>Replace</button>
              </div>
            </div>
          );
        })}

        <button className="row gap8" onClick={onAdjust}
          style={{ width: '100%', justifyContent: 'center', border: '1.5px dashed var(--line)',
            background: 'transparent', cursor: 'pointer', borderRadius: 'var(--r)', padding: '15px',
            color: 'var(--ink-2)', fontWeight: 600, fontSize: 14.5, fontFamily: 'var(--font-body)', marginTop: 4 }}>
          <I2 name="sun" size={17} /> Adjust interests or time
        </button>
      </div>

      <div className="screen-pad" style={{ flex: '0 0 auto', padding: '12px 22px 30px',
        background: 'linear-gradient(180deg, rgba(244,236,221,0), var(--sand) 36%)' }}>
        <Btn2 variant="primary" icon="reroll" onClick={onRegenerate} disabled={replacing === 0}>
          {replacing === 0 ? 'Toggle a stop to reroll' : `Reroll ${replacing} stop${replacing > 1 ? 's' : ''}`}
        </Btn2>
      </div>
    </div>
  );
}

Object.assign(window, { ItineraryScreen, StopDetailScreen, RerollScreen, DriveConnector, StopRow });
