// Journey screen — stats from /api/journey
const { useState: useState_J, useEffect: useEffect_J } = React;

const PHASE_NAMES = { 1: "FOUNDATION", 2: "EXPLORATION", 3: "BUILDING", 4: "COMPOUND" };
const PHASE_LENGTH = 30;
const prettyTheme = (t) => (t || "unknown").replace(/_/g, " ").replace(/\b\w/g, c => c.toUpperCase());

function JourneyScreen({ onSettings }) {
  const [journey, setJourney] = useState_J(null);
  const [err, setErr] = useState_J(null);

  useEffect_J(() => {
    api.getJourney().then(setJourney).catch(e => { console.warn("/api/journey failed:", e); setErr(e); });
  }, []);

  if (err || !journey) {
    return (
      <div className="screen">
        <div className="topbar-row" style={{ paddingTop: 28 }}>
          <div><div className="greet">Your journey</div><div className="sub">Loading…</div></div>
          <button className="gear-btn" onClick={onSettings} aria-label="Settings"><IconGear/></button>
        </div>
      </div>
    );
  }

  const { streak, total_days, avg_rating, moved_pct, phase, theme_ratings, sparkline_7 } = journey;

  if (total_days === 0) {
    return (
      <div className="screen">
        <div className="topbar-row" style={{ paddingTop: 28 }}>
          <div><div className="greet">Your journey</div><div className="sub">Just getting started</div></div>
          <button className="gear-btn" onClick={onSettings} aria-label="Settings"><IconGear/></button>
        </div>
        <div className="empty-state">
          <div className="empty-body">No entries yet. The first one is the hardest.</div>
        </div>
      </div>
    );
  }

  const phaseName = PHASE_NAMES[phase] || "FOUNDATION";
  const phaseProgress = total_days % PHASE_LENGTH || (total_days === 0 ? 0 : PHASE_LENGTH);

  const themesSorted = Object.entries(theme_ratings || {})
    .sort((a, b) => b[1] - a[1])
    .slice(0, 4);

  const max = Math.max(5, ...(sparkline_7 || [1]));
  const bars = sparkline_7 || [0,0,0,0,0,0,0];

  const today = new Date();
  const labels = Array.from({ length: 7 }, (_, i) => {
    const d = new Date(today); d.setDate(today.getDate() - (6 - i));
    return ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][d.getDay()];
  });

  return (
    <div className="screen">
      <div className="topbar-row" style={{ paddingTop: 28 }}>
        <div>
          <div className="greet">Your journey</div>
          <div className="sub">{streak ? `Streak: ${streak}` : "Building"}</div>
        </div>
        <button className="gear-btn" onClick={onSettings} aria-label="Settings"><IconGear/></button>
      </div>
      <div style={{ height: 12 }}/>

      <div className="stat-row">
        <StatCard label="Days" value={String(total_days)}/>
        <StatCard label="Moved" value={String(moved_pct)} unit="%"/>
        <StatCard label="Avg" value={avg_rating ? avg_rating.toFixed(1) : "—"}/>
      </div>

      <div className="phase-block">
        <div className="phase-head">
          <div className="phase-title">PHASE {phase} · {phaseName}</div>
          <div className="phase-count">{phaseProgress} / {PHASE_LENGTH}</div>
        </div>
        <div className="phase-bar"><span style={{ width: `${(phaseProgress / PHASE_LENGTH) * 100}%` }}/></div>
      </div>

      {themesSorted.length > 0 && (
        <div className="insights">
          <h3>What&rsquo;s landing</h3>
          {themesSorted.map(([t, v]) => (
            <div key={t} className="insight-row">
              <span className="insight-dot"/>
              <span className="insight-name">{prettyTheme(t)}</span>
              <span className="insight-value">{v.toFixed(1)} <span className="star-tiny">★</span></span>
            </div>
          ))}
        </div>
      )}

      <div className="sparkline-wrap">
        <div className="sparkline-label">Last 7 days</div>
        <div className="sparkline">
          {bars.map((v, i) => (
            <div
              key={i}
              className={`bar ${i === bars.length - 1 ? "last" : ""}`}
              style={{ height: `${v ? (v / max) * 100 : 3}%` }}
            />
          ))}
        </div>
        <div style={{
          display: "flex", justifyContent: "space-between",
          fontSize: 11, color: "var(--text-faint)",
          marginTop: 8, letterSpacing: ".12em", textTransform: "uppercase"
        }}>
          {labels.map((l, i) => <span key={i}>{l}</span>)}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { JourneyScreen });
