// Step 1 — Plan Your Visit (river + activity + live conditions)

// ── Source badge ─────────────────────────────────────────────────────────────
function SourceBadge({ source }) {
  if (source === 'live')    return <span style={step1Styles.live}>Live</span>;
  if (source === 'cached')  return <span style={step1Styles.cached}>Cached</span>;
  if (source === 'stale')   return <span style={{ fontSize: 'var(--fs-2)', fontWeight: 'var(--fw-bold)', color: 'var(--theme-color-warning-dark)', background: 'var(--theme-color-warning-lighter)', padding: '2px 8px', borderRadius: 'var(--radius-pill)' }}>Stale</span>;
  return                           <span style={step1Styles.estimated}>Estimated</span>;
}

// Human relative time — "3 hours ago", "yesterday", "4 days ago"
function relativeTime(ts) {
  const mins = Math.round((Date.now() - ts) / 60000);
  if (mins < 2) return 'a moment ago';
  if (mins < 60) return mins + ' minutes ago';
  const hours = Math.round(mins / 60);
  if (hours < 2) return 'an hour ago';
  if (hours < 24) return hours + ' hours ago';
  const days = Math.round(hours / 24);
  if (days < 2) return 'yesterday';
  return days + ' days ago';
}

const step1Styles = {
  live:      { fontSize: 'var(--fs-2)', fontWeight: 'var(--fw-bold)', color: 'var(--theme-color-success-darker)', background: 'var(--theme-color-success-lighter)', padding: '2px 8px', borderRadius: 'var(--radius-pill)', whiteSpace: 'nowrap' },
  cached:    { fontSize: 'var(--fs-2)', fontWeight: 'var(--fw-bold)', color: 'var(--theme-color-info-darker)',    background: 'var(--theme-color-info-lighter)',    padding: '2px 8px', borderRadius: 'var(--radius-pill)', whiteSpace: 'nowrap' },
  estimated: { fontSize: 'var(--fs-2)', fontWeight: 'var(--fw-bold)', color: 'var(--fg3)',                        background: 'var(--bg3)',                          padding: '2px 8px', borderRadius: 'var(--radius-pill)', whiteSpace: 'nowrap' },
};

function formatFlow(cfs) {
  if (cfs == null) return null;
  return cfs >= 1000 ? (cfs / 1000).toFixed(1) + 'k cfs' : Math.round(cfs) + ' cfs';
}

// ── Activity selector ────────────────────────────────────────────────────────
function ActivitySelector({ value, onChange }) {
  return (
    <div className="usa-card">
      <div className="usa-card__header">
        <h3 className="usa-card__header-title">What will you be doing?</h3>
      </div>
      <div className="usa-card__body">
        <p className="usa-hint" style={{ marginBottom: 'var(--sp-2)' }}>
          Select your primary activity. This personalises the safety guidance on your results.
        </p>
        <fieldset style={{ border: 'none', margin: 0, padding: 0 }}>
          <legend className="sr-only">Select your river activity</legend>
          <div className="rs-activity-grid">
            {ACTIVITY_TYPES.map(act => (
              <div key={act.id} className="rs-radio-tile">
                <input
                  className="usa-radio__input"
                  type="radio"
                  id={`activity-${act.id}`}
                  name="activity"
                  value={act.id}
                  checked={value === act.id}
                  onChange={() => onChange(act.id)}
                />
                <label
                  htmlFor={`activity-${act.id}`}
                  className={`rs-radio-tile__label${value === act.id ? ' rs-radio-tile__label--selected' : ''}`}
                >
                  {act.label}
                </label>
              </div>
            ))}
          </div>
        </fieldset>
      </div>
    </div>
  );
}

// ── Conditions panel ─────────────────────────────────────────────────────────
function ConditionsPanel({ conditions, loading, onRefresh }) {
  if (loading) {
    return (
      <div className="usa-card">
        <div className="usa-card__header">
          <h3 className="usa-card__header-title">Current conditions</h3>
        </div>
        <div className="usa-card__body" style={{ textAlign: 'center', padding: 'var(--sp-4)' }}>
          <p style={{ color: 'var(--fg3)', fontSize: 'var(--fs-4)', margin: 0 }}>
            Loading live data from USGS and NWS…
          </p>
        </div>
      </div>
    );
  }

  const anyLive    = conditions && Object.values(conditions.source).includes('live');
  const anyCached  = conditions && Object.values(conditions.source).includes('cached');
  const anyStale   = conditions && Object.values(conditions.source).includes('stale');
  const overall    = !conditions ? 'estimated' : anyLive ? 'live' : anyCached ? 'cached' : anyStale ? 'stale' : 'estimated';

  let lastUpdatedLabel = null;
  if (conditions?.lastUpdated) {
    const dt = new Date(conditions.lastUpdated);
    lastUpdatedLabel = dt.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }) +
      ', ' + dt.toLocaleDateString([], { month: 'short', day: 'numeric' });
  }

  const tdL = { padding: 'var(--sp-1) 0', borderBottom: '1px solid var(--border-subtle)', color: 'var(--fg2)', width: '50%', fontSize: 'var(--fs-4)', verticalAlign: 'middle' };
  const tdR = { padding: 'var(--sp-1) 0', borderBottom: '1px solid var(--border-subtle)', fontWeight: 'var(--fw-semibold)', textAlign: 'right', fontSize: 'var(--fs-4)', verticalAlign: 'middle' };
  const sub = { fontSize: 'var(--fs-2)', marginLeft: 4, color: 'var(--fg3)' };

  return (
    <div className="usa-card">
      <div className="usa-card__header">
        <h3 className="usa-card__header-title" style={{ justifyContent: 'space-between' }}>
          <span>Current conditions</span>
          <span style={{ display: 'flex', alignItems: 'center', gap: 'var(--sp-1)' }}>
            <SourceBadge source={overall} />
            <button onClick={onRefresh} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--fg-link)', fontSize: 'var(--fs-3)', fontFamily: 'var(--font-sans)', padding: 0, textDecoration: 'underline', textUnderlineOffset: '2px' }}>
              Refresh
            </button>
          </span>
        </h3>
      </div>
      <div className="usa-card__body" style={{ padding: 'var(--sp-2) var(--sp-3)' }}>

        {/* Active alerts */}
        {conditions?.waterAlerts?.map((alert, i) => (
          <div key={i} className={`usa-alert usa-alert--${alert.severity === 'extreme' ? 'error' : 'warning'}`} role="alert" style={{ marginBottom: 'var(--sp-2)' }}>
            <div>
              <p className="usa-alert__heading">{alert.event}</p>
              <p className="usa-alert__text">{alert.headline}</p>
            </div>
          </div>
        ))}

        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <tbody>
            <tr>
              <td style={tdL}>Water temperature <span style={sub}>USGS</span></td>
              <td style={tdR}>
                {conditions?.waterTempF != null
                  ? <span>{conditions.waterTempF}°F <SourceBadge source={conditions.source.usgs} /></span>
                  : <span style={{ color: 'var(--fg3)' }}>No sensor data</span>}
              </td>
            </tr>
            <tr>
              <td style={tdL}>Stream flow <span style={sub}>USGS</span></td>
              <td style={tdR}>
                {conditions?.discharge != null
                  ? <span>{formatFlow(conditions.discharge)} <SourceBadge source={conditions.source.usgs} /></span>
                  : <span style={{ color: 'var(--fg3)' }}>—</span>}
              </td>
            </tr>
            <tr>
              <td style={tdL}>Gauge height <span style={sub}>USGS</span></td>
              <td style={tdR}>
                {conditions?.gaugeHeight != null
                  ? <span>{conditions.gaugeHeight.toFixed(1)} ft <SourceBadge source={conditions.source.usgs} /></span>
                  : <span style={{ color: 'var(--fg3)' }}>—</span>}
              </td>
            </tr>
            <tr>
              <td style={tdL}>Air temperature <span style={sub}>NWS</span></td>
              <td style={tdR}>
                {conditions?.airTempF != null
                  ? <span>{conditions.airTempF}°F <SourceBadge source={conditions.source.forecast} /></span>
                  : <span style={{ color: 'var(--fg3)' }}>—</span>}
              </td>
            </tr>
            {conditions?.forecastText && (
              <tr>
                <td style={{ ...tdL, borderBottom: 'none' }}>Forecast <span style={sub}>NWS</span></td>
                <td style={{ ...tdR, borderBottom: 'none', fontSize: 'var(--fs-3)' }}>
                  {conditions.forecastText}
                  {conditions.windSpeed && <span style={{ color: 'var(--fg3)', fontWeight: 'var(--fw-normal)' }}> · {conditions.windSpeed}</span>}
                </td>
              </tr>
            )}
          </tbody>
        </table>

        {!conditions && (
          <p style={{ fontSize: 'var(--fs-3)', color: 'var(--fg3)', margin: 'var(--sp-1) 0 0', fontStyle: 'italic' }}>
            Live data unavailable. Using estimated values — adjust the slider if you have current readings.
          </p>
        )}
        {anyStale && conditions.staleAsOf && (
          <p style={{ fontSize: 'var(--fs-3)', color: 'var(--theme-color-warning-dark)', margin: 'var(--sp-1) 0 0' }}>
            Data from {relativeTime(conditions.staleAsOf)} — live update unavailable.
          </p>
        )}
        {lastUpdatedLabel && (
          <p style={{ fontSize: 'var(--fs-2)', color: 'var(--fg3)', margin: 'var(--sp-105) 0 0', textAlign: 'right' }}>
            Data as of {lastUpdatedLabel}
          </p>
        )}
      </div>
    </div>
  );
}

// ── Main step component ──────────────────────────────────────────────────────
function StepPlan({ data, onUpdate, conditions, conditionsLoading, onRefreshConditions }) {
  const [locStatus, setLocStatus] = React.useState('idle');
  const [locLabel, setLocLabel]   = React.useState('');
  const [locError, setLocError]   = React.useState('Location unavailable. Please select a river manually.');
  const [nearbyRivers, setNearbyRivers] = React.useState([]);

  const tempMeta  = getWaterTempMeta(data.waterTemp);
  const riverMeta = data.river ? getRiverData(data.river) : null;

  function handleRiverChange(name) {
    const river = getRiverData(name);
    onUpdate({ river: name, waterTemp: river?.waterTemp ?? data.waterTemp, airTemp: river?.airTemp ?? data.airTemp });
  }

  async function handleLocate() {
    if (!navigator.geolocation) {
      setLocError('This browser does not support location. Please select a river manually.');
      setLocStatus('error');
      return;
    }
    setLocStatus('loading');
    navigator.geolocation.getCurrentPosition(
      async pos => {
        const { latitude: lat, longitude: lng } = pos.coords;
        try {
          // Try live USGS discovery first
          const discovered = await fetchNearbyUSGSSites(lat, lng, 60);
          if (discovered.length > 0) {
            discovered.forEach(s => registerDiscoveredSite(s));
            setNearbyRivers(discovered);
            handleRiverChange(discovered[0].name);
            setLocLabel(`${discovered.length} active gauge${discovered.length > 1 ? 's' : ''} found near you via USGS`);
          } else {
            // Fall back to static list
            const nearby = getNearbyRivers(lat, lng);
            setNearbyRivers(nearby);
            if (nearby.length > 0) handleRiverChange(nearby[0].name);
            setLocLabel(nearby.length > 0 ? `${nearby.length} rivers found near you` : 'No rivers found within 500 miles');
          }
        } catch {
          const nearby = getNearbyRivers(lat, lng);
          setNearbyRivers(nearby);
          if (nearby.length > 0) handleRiverChange(nearby[0].name);
          setLocLabel(nearby.length > 0 ? `${nearby.length} rivers found near you` : 'No rivers found nearby');
        }
        setLocStatus('done');
      },
      err => {
        // 1 = PERMISSION_DENIED · 2 = POSITION_UNAVAILABLE · 3 = TIMEOUT
        if (err.code === 1) {
          setLocError('Location access was blocked. Enable location for this site in your browser settings, or select a river manually below.');
        } else if (err.code === 3) {
          setLocError('Locating timed out. Check your connection and try again, or select a river manually.');
        } else {
          setLocError('Could not determine your location. Please select a river manually.');
        }
        setLocStatus('error');
      },
      { enableHighAccuracy: false, timeout: 10000, maximumAge: 300000 }
    );
  }

  const allRivers   = RIVERS.map(r => r.name);
  const nearbyNames = nearbyRivers.map(r => r.name);

  return (
    <div>
      <h2 className="rs-step-title">Plan your visit</h2>
      <p className="rs-step-desc">Select your river and activity. Live conditions will load automatically from USGS and NWS.</p>

      {/* River selector */}
      <div className="usa-card">
        <div className="usa-card__header">
          <h3 className="usa-card__header-title">River destination</h3>
        </div>
        <div className="usa-card__body">
          <div className="usa-form-group">
            <label className="usa-label" htmlFor="river-select">Select a river</label>
            <select
              id="river-select"
              className="usa-select"
              value={data.river}
              onChange={e => handleRiverChange(e.target.value)}
            >
              <option value="">Choose a river…</option>

              {nearbyNames.length > 0 && (
                <optgroup label="Near your location">
                  {nearbyNames.map(name => {
                    const r = nearbyRivers.find(x => x.name === name);
                    return (
                      <option key={name} value={name}>
                        {name} ({r.state || '??'}) — {r.distance} mi
                        {r.isDiscovered ? ' · USGS' : ''}
                      </option>
                    );
                  })}
                </optgroup>
              )}

              <optgroup label={nearbyNames.length > 0 ? 'All rivers' : 'Select a river'}>
                {allRivers.filter(n => !nearbyNames.includes(n)).map(name => {
                  const r = getRiverData(name);
                  return <option key={name} value={name}>{name} ({r.state})</option>;
                })}
              </optgroup>
            </select>
          </div>

          <button className="rs-location-btn" onClick={handleLocate} disabled={locStatus === 'loading'}>
            {locStatus === 'loading' ? '⟳ Locating…' : '◎ Use my location'}
          </button>

          {locStatus === 'done' && locLabel && (
            <p style={{ fontSize: 'var(--fs-3)', color: 'var(--theme-color-success-darker)', marginTop: 'var(--sp-05)' }}>✓ {locLabel}</p>
          )}
          {locStatus === 'error' && (
            <p style={{ fontSize: 'var(--fs-3)', color: 'var(--theme-color-error)', marginTop: 'var(--sp-05)' }}>
              {locError}
            </p>
          )}

          {data.river && (
            <div className="rs-river-pill" style={{ marginTop: 'var(--sp-2)' }}>
              <span>📍</span>
              <span>{data.river} {riverMeta ? `(${riverMeta.state || 'USGS'})` : ''}</span>
            </div>
          )}
        </div>
      </div>

      {/* Activity selector */}
      <ActivitySelector value={data.activity} onChange={activity => onUpdate({ activity })} />

      {/* Live conditions — once river is selected */}
      {data.river && (
        <ConditionsPanel conditions={conditions} loading={conditionsLoading} onRefresh={onRefreshConditions} />
      )}

      {/* Water temperature slider */}
      {data.river && (
        <div className="usa-card">
          <div className="usa-card__header">
            <h3 className="usa-card__header-title" style={{ gap: 'var(--sp-105)' }}>
              Water temperature
              <SourceBadge source={conditions?.source?.usgs && conditions.source.usgs !== 'unavailable' ? conditions.source.usgs : 'estimated'} />
            </h3>
          </div>
          <div className="usa-card__body">
            <p className="usa-hint" style={{ marginBottom: 'var(--sp-105)' }}>
              {conditions?.waterTempF
                ? 'Loaded from USGS gauge. Adjust if you have a more current reading.'
                : 'Estimated from historical data. Adjust to match current conditions.'}
            </p>
            <div className="rs-slider-value-row">
              <span className="rs-slider-value">{data.waterTemp}°F</span>
              <span className={`rs-temp-badge rs-temp-badge--${tempMeta.cls}`}>{tempMeta.label}</span>
            </div>
            <input type="range" min={32} max={90} value={data.waterTemp}
              onChange={e => onUpdate({ waterTemp: Number(e.target.value) })}
              aria-label={`Water temperature: ${data.waterTemp}°F`} />
            <div className="rs-slider-labels"><span>32°F</span><span>90°F</span></div>
          </div>
        </div>
      )}

      {/* Cold water warning */}
      {data.waterTemp < 70 && data.river && (
        <div className="usa-alert usa-alert--warning" role="note">
          <div>
            <p className="usa-alert__heading">Cold water hazard</p>
            <p className="usa-alert__text">
              At {data.waterTemp}°F, cold shock can occur within seconds of immersion. Even strong swimmers lose muscle control after 10–30 minutes.
            </p>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { StepPlan });
