/* global React, window */
const { TapedPhoto, Sketch, FieldLine, LogoLong, LogoStayLonesome, LogoGoat, GoatOrnament, SignOff, NOTES } = window;

/*
 * Home — quiet horizon hero, latest dispatch, three doors.
 * No more circular coin/medallion. The hero now centers on the
 * horizontal lockup over a hand-drawn ridge, big and quiet.
 */

// ----- Far West Texas night sky -----
// Deterministic star scatter so the field is stable across renders.
function makeStars(count, seed, opts) {
  const o = opts || {};
  const xMax = o.xMax || 1600;
  const yMax = o.yMax || 360;
  const arr = [];
  let s = seed;
  const next = () => { s = (s * 9301 + 49297) % 233280; return s / 233280; };
  for (let i = 0; i < count; i++) {
    const x = next() * xMax;
    const y = next() * yMax;
    const t = next();
    const r = t < 0.86 ? 0.35 + t * 0.7 : 1.05 + (t - 0.86) * 6.2;
    const op = 0.32 + next() * 0.62;
    arr.push([x, y, r, op]);
  }
  return arr;
}
const NIGHT_STARS = makeStars(260, 1337);
const MILKY_STARS = makeStars(120, 4242, { xMax: 1600, yMax: 220 }).
  map(([x, y, r, op]) => {
    const ny = 70 + y * 0.55 + (x - 800) * 0.12;
    return [x, ny, r * 0.9, Math.min(0.95, op + 0.1)];
  });
const HERO_STARS = [[210, 110, 1.8], [640, 70, 2.2], [1090, 140, 1.6], [1430, 95, 2.0], [380, 220, 1.5]];
// Mark the brighter stars to twinkle; varied durations & delays so it's not synced.
const TWINKLE = NIGHT_STARS.
  map((s, i) => [s, i]).
  filter(([s]) => s[2] > 0.95).
  slice(0, 28).
  map(([s, i], k) => ({ i, dur: 2.4 + (k * 0.37) % 3.6, delay: (k * 0.91) % 5 }));

// ----- Color & easing helpers -----
function _rgb(h) { const n = parseInt(h.slice(1), 16); return [(n >> 16) & 255, (n >> 8) & 255, n & 255]; }
function _lerp(a, b, t) { return a + (b - a) * t; }
function _lerpHex(c1, c2, t) {
  const a = _rgb(c1), b = _rgb(c2);
  return `rgb(${(_lerp(a[0], b[0], t)) | 0},${(_lerp(a[1], b[1], t)) | 0},${(_lerp(a[2], b[2], t)) | 0})`;
}
function lerpStops(t, stops) {
  if (t <= stops[0][0]) return stops[0][1];
  for (let i = 0; i < stops.length - 1; i++) {
    if (t <= stops[i + 1][0]) {
      const p = (t - stops[i][0]) / (stops[i + 1][0] - stops[i][0]);
      return _lerpHex(stops[i][1], stops[i + 1][1], Math.max(0, Math.min(1, p)));
    }
  }
  return stops[stops.length - 1][1];
}
function lerpNum(t, stops) {
  if (t <= stops[0][0]) return stops[0][1];
  for (let i = 0; i < stops.length - 1; i++) {
    if (t <= stops[i + 1][0]) {
      const p = (t - stops[i][0]) / (stops[i + 1][0] - stops[i][0]);
      return _lerp(stops[i][1], stops[i + 1][1], Math.max(0, Math.min(1, p)));
    }
  }
  return stops[stops.length - 1][1];
}
function clamp01(x) { return Math.max(0, Math.min(1, x)); }
function easeInOutCubic(p) { return p < 0.5 ? 4 * p * p * p : 1 - Math.pow(-2 * p + 2, 3) / 2; }

// ----- Chisos panorama (after the view of Casa Grande from the desert floor) -----
// Layered atmospheric ridges: pale haze in back, the iconic flat-topped Casa
// Grande as the centerpiece, then closer foothills, then near foreground.
// The tiered profile around x=860–1100 is Casa Grande's lower shoulder, main
// flat top, and right shoulder — its "house" silhouette.
const FAR_PATH = "M 0 380 L 120 365 L 260 376 L 400 358 L 540 372 L 680 354 L 820 368 L 960 350 L 1100 372 L 1240 354 L 1380 374 L 1520 358 L 1600 370 L 1600 600 L 0 600 Z";
const CHISOS_PATH = [
  "M 0 396",
  "L 80 388 L 160 396 L 240 384 L 340 396 L 440 380 L 540 388 L 620 372",
  "L 700 380 L 760 372 L 820 358 L 860 320",   // approach + Casa Grande west wall
  "L 880 320",                                   // CG lower-left shoulder
  "L 900 290 L 1020 290",                        // CG main flat top
  "L 1040 310 L 1080 310",                       // CG right shoulder
  "L 1100 332 L 1170 372 L 1220 360 L 1270 384", // descending CG, neighbouring sub-peak
  "L 1340 380 L 1420 388 L 1500 380 L 1600 392",
  "L 1600 600 L 0 600 Z"
].join(" ");
const MID_PATH = "M 0 446 L 100 438 L 220 452 L 340 426 L 460 444 L 580 422 L 700 432 L 820 418 L 940 430 L 1060 414 L 1180 426 L 1300 412 L 1420 426 L 1540 416 L 1600 422 L 1600 600 L 0 600 Z";
const FRONT_PATH = "M 0 510 L 90 498 L 200 516 L 320 488 L 460 514 L 580 490 L 720 510 L 860 488 L 1000 510 L 1160 490 L 1320 508 L 1480 488 L 1600 508 L 1600 600 L 0 600 Z";

// ----- HorizonScene: smooth sunset/sunrise transition -----
function HorizonScene({ dark }) {
  // t = 0 → full day, t = 1 → full night.
  // The day/night toggle in the nav drives this — the whole scene transitions
  // smoothly through twilight: sun sets, sky shifts, moon rises, stars fade in.
  const [t, setT] = React.useState(dark ? 1 : 0);
  const tRef = React.useRef(t);
  tRef.current = t;
  const animRef = React.useRef(null);

  React.useEffect(() => {
    const target = dark ? 1 : 0;
    const from = tRef.current;
    if (from === target) return;
    const dur = 4500;
    const start = performance.now();
    const step = (now) => {
      const p = Math.min(1, (now - start) / dur);
      const e = easeInOutCubic(p);
      const v = from + (target - from) * e;
      tRef.current = v;
      setT(v);
      if (p < 1) animRef.current = requestAnimationFrame(step);
      else animRef.current = null;
    };
    animRef.current = requestAnimationFrame(step);
    return () => {
      if (animRef.current) { cancelAnimationFrame(animRef.current); animRef.current = null; }
    };
  }, [dark]);

  // Sky gradient — day → twilight (warm orange/pink) → indigo → night.
  const skyTop = lerpStops(t, [[0, '#E0D3B0'], [0.40, '#b585a8'], [0.55, '#5b4988'], [0.72, '#0e1622'], [1, '#04070a']]);
  const skyMid = lerpStops(t, [[0, '#F3EAD7'], [0.40, '#e2925a'], [0.55, '#9c4838'], [0.72, '#1a1b2a'], [1, '#0a1014']]);
  const skyBot = lerpStops(t, [[0, '#E0D3B0'], [0.40, '#f4c47a'], [0.55, '#d77840'], [0.72, '#2a1a30'], [1, '#10161c']]);

  // Sun: cx=1180. Stays high then sets fast; color shifts gold → red as it dips.
  const sunY = lerpNum(t, [[0, 220], [0.30, 240], [0.55, 470], [0.65, 600], [1, 620]]);
  const sunOp = clamp01(lerpNum(t, [[0, 0.9], [0.45, 0.85], [0.6, 0], [1, 0]]));
  const sunColor = lerpStops(t, [[0, '#C89A4E'], [0.40, '#e89a4a'], [0.55, '#d24a25']]);

  // Moon: cx=420 (opposite side). Hidden until past sunset, rises into night.
  const moonY = lerpNum(t, [[0, 620], [0.45, 600], [0.7, 320], [1, 200]]);
  const moonOp = clamp01(lerpNum(t, [[0, 0], [0.5, 0], [0.85, 0.95], [1, 0.95]]));
  const moonGlow = clamp01(lerpNum(t, [[0, 0], [0.6, 0], [1, 0.35]]));

  // Stars/Milky Way fade in past sunset.
  const starsOp = clamp01((t - 0.55) / 0.4);
  const milkyOp = clamp01((t - 0.6) / 0.4);
  const heroStarOp = clamp01((t - 0.5) / 0.4);

  // Atmospheric perspective: by day, ridges fade from pale dusty blue (far)
  // to deep blue (near). Through twilight, all layers shift through warm
  // mauve/plum and into night silhouettes.
  const farFill = lerpStops(t, [[0, '#bccada'], [0.40, '#cdb0a6'], [0.55, '#85607a'], [0.72, '#1f2734'], [1, '#212a36']]);
  const farOp   = lerpNum(t,   [[0, 0.55], [0.40, 0.65], [0.55, 0.85], [0.72, 1], [1, 1]]);
  const chisosFill = lerpStops(t, [[0, '#8a9bae'], [0.40, '#a07a72'], [0.55, '#5a3a48'], [0.72, '#181f2a'], [1, '#171e28']]);
  const chisosOp   = lerpNum(t, [[0, 0.78], [0.40, 0.90], [0.55, 1], [1, 1]]);
  const midFill = lerpStops(t, [[0, '#5d7185'], [0.40, '#553544'], [0.55, '#2c1924'], [0.72, '#0f141c'], [1, '#0e141c']]);
  const midOp   = lerpNum(t,   [[0, 0.92], [0.55, 1], [1, 1]]);
  const frontFill = lerpStops(t, [[0, '#384858'], [0.40, '#1f1018'], [0.55, '#0e0610'], [1, '#06090d']]);

  return (
    <svg className="horizon" viewBox="0 0 1600 600" preserveAspectRatio="xMidYMid slice" aria-hidden="true">
      <defs>
        <linearGradient id="sky-grad" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0" stopColor={skyTop} />
          <stop offset="0.55" stopColor={skyMid} />
          <stop offset="1" stopColor={skyBot} />
        </linearGradient>
        <radialGradient id="milky-band" cx="50%" cy="50%" r="50%">
          <stop offset="0" stopColor="#e8d9b4" stopOpacity="0.10" />
          <stop offset="0.55" stopColor="#cbd6e6" stopOpacity="0.045" />
          <stop offset="1" stopColor="#e8d9b4" stopOpacity="0" />
        </radialGradient>
        <radialGradient id="star-glow" cx="50%" cy="50%" r="50%">
          <stop offset="0" stopColor="#fff7e0" stopOpacity="0.9" />
          <stop offset="1" stopColor="#fff7e0" stopOpacity="0" />
        </radialGradient>
        <radialGradient id="sun-glow" cx="50%" cy="50%" r="50%">
          <stop offset="0" stopColor={sunColor} stopOpacity="0.45" />
          <stop offset="1" stopColor={sunColor} stopOpacity="0" />
        </radialGradient>
        {/* Crescent mask — white = visible moon, black = the carved-out side.
            Used in user space so the cutout is truly transparent (no painted
            disc that fights the sky gradient behind it). */}
        <mask id="moon-crescent" maskUnits="userSpaceOnUse" x="-60" y="-70" width="120" height="140">
          <circle r="46" fill="white" />
          <circle cx="16" cy="-10" r="42" fill="black" />
        </mask>
      </defs>

      {/* sky */}
      <rect x="0" y="0" width="1600" height="600" fill="url(#sky-grad)" />

      {/* Milky Way diffuse band (only visible past sunset) */}
      {milkyOp > 0.01 &&
        <ellipse cx="800" cy="200" rx="950" ry="110" fill="url(#milky-band)" opacity={milkyOp} transform="rotate(-10 800 200)" />
      }

      {/* Stars — group opacity fades in across sunset. Twinkle classes are per-star. */}
      {starsOp > 0.01 &&
        <g opacity={starsOp}>
          <g fill="#e8d9b4">
            {NIGHT_STARS.map(([x, y, r, op], i) => {
              const tw = TWINKLE.find(z => z.i === i);
              return (
                <circle
                  key={"s" + i}
                  cx={x} cy={y} r={r}
                  opacity={op}
                  className={tw ? "lg-star-twinkle" : undefined}
                  style={tw ? {
                    animationDuration: tw.dur + "s",
                    animationDelay: tw.delay + "s",
                    "--lg-base-op": op
                  } : undefined}
                />
              );
            })}
          </g>
          <g fill="#f3ead0" opacity={milkyOp}>
            {MILKY_STARS.map(([x, y, r, op], i) =>
              <circle key={"m" + i} cx={x} cy={y} r={r} opacity={op} />
            )}
          </g>
          <g opacity={heroStarOp}>
            {HERO_STARS.map(([x, y, r], i) =>
              <g key={"b" + i} transform={`translate(${x} ${y})`}>
                <circle r={r * 5} fill="url(#star-glow)" opacity="0.55" />
                <circle r={r} fill="#fff7e0" opacity="0.95" />
              </g>
            )}
          </g>

          {/* Shooting stars — rare, subtle. Three streaks with long delays so they
              fire occasionally and not all at once. */}
          <g className="lg-shoot-layer">
            <g transform="translate(180 90)"><g className="lg-shoot lg-shoot-1">
              <line x1="0" y1="0" x2="-78" y2="-22" stroke="#fff7e0" strokeWidth="1.2" opacity="0.55" />
              <line x1="0" y1="0" x2="-36" y2="-10" stroke="#fff7e0" strokeWidth="1.6" opacity="0.95" />
              <circle r="1.7" fill="#fff7e0" />
            </g></g>
            <g transform="translate(1240 70)"><g className="lg-shoot lg-shoot-2">
              <line x1="0" y1="0" x2="64" y2="-18" stroke="#fff7e0" strokeWidth="1.2" opacity="0.55" />
              <line x1="0" y1="0" x2="30" y2="-8" stroke="#fff7e0" strokeWidth="1.6" opacity="0.95" />
              <circle r="1.5" fill="#fff7e0" />
            </g></g>
            <g transform="translate(720 50)"><g className="lg-shoot lg-shoot-3">
              <line x1="0" y1="0" x2="-92" y2="-16" stroke="#fff7e0" strokeWidth="1.2" opacity="0.5" />
              <line x1="0" y1="0" x2="-44" y2="-8" stroke="#fff7e0" strokeWidth="1.6" opacity="0.95" />
              <circle r="1.6" fill="#fff7e0" />
            </g></g>
          </g>
        </g>
      }

      {/* Sun with soft glow */}
      {sunOp > 0.01 &&
        <g opacity={sunOp}>
          <circle cx="1180" cy={sunY} r="120" fill="url(#sun-glow)" />
          <circle cx="1180" cy={sunY} r="56" fill={sunColor} />
        </g>
      }

      {/* Moon — true crescent via SVG mask (no painted bite-out disc) */}
      {moonOp > 0.01 &&
        <g transform={`translate(420 ${moonY})`} opacity={moonOp}>
          <circle r="120" fill="url(#star-glow)" opacity={moonGlow} />
          <circle r="46" fill="#e8d9b4" opacity="0.95" mask="url(#moon-crescent)" />
        </g>
      }

      {/* Chisos panorama — atmospheric layered ridges with Casa Grande as centerpiece */}
      <path d={FAR_PATH} fill={farFill} fillOpacity={farOp} />
      <path d={CHISOS_PATH} fill={chisosFill} fillOpacity={chisosOp} />
      <path d={MID_PATH} fill={midFill} fillOpacity={midOp} />
      <path d={FRONT_PATH} fill={frontFill} />
    </svg>
  );
}

function Home({ go, dark }) {
  // Prefer the most recently saved real entry from Field Desk; fall back
  // to the seeded NOTES only if there are no real entries yet.
  const savedEntries = (window.LGStore && window.LGStore.list) ? window.LGStore.list("entries") : [];
  const latestSaved = savedEntries[0];
  const latest = latestSaved
    ? {
        id: latestSaved.id,
        no: "FN-" + (latestSaved.id || "").slice(-3).toUpperCase(),
        title: latestSaved.title || "Untitled",
        date: latestSaved.date || "",
        location: latestSaved.location || "n/a",
        weather: latestSaved.weather || "n/a",
        excerpt: latestSaved.preview || (latestSaved.body ? latestSaved.body.slice(0, 160) + "…" : ""),
        photoCaption: latestSaved.title || "Filed entry",
        heroImage: latestSaved.heroImage || ""
      }
    : NOTES[0];
  return (
    <main>
      {/* HERO ============================================ */}
      <section className="home-hero">
        <HorizonScene dark={dark} />
        <div className="home-hero__content container">
          <span className="eyebrow home-hero__eyebrow">Lonesome Goat · Est. MMXXV · West Texas</span>

          {/* Stay Lonesome lockup — flips with daylight/moonlight */}
          <div className="home-hero__lockup">
            <LogoStayLonesome height={320} dark={dark} />
          </div>

          <h1 className="display home-hero__line" style={{ display: 'none' }}>
            <br />
          </h1>
          <p className="serif home-hero__sub">
            Adventure, story, and community for the over-connected and under-adventured.
          </p>
          <div className="home-hero__cta">
            <button className="btn" onClick={() => go("desk")}>Enter the Field Desk →</button>
            <button className="btn btn--ghost" onClick={() => go("manifesto")}>Read the manifesto</button>
          </div>
        </div>
      </section>

      {/* LATEST DISPATCH ================================== */}
      <section className="container" style={{ paddingTop: 120, paddingBottom: 120 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 20, marginBottom: 36 }}>
          <span className="eyebrow">Latest dispatch</span>
          <span style={{ flex: 1, height: 1, background: 'var(--rule)' }} />
          <span className="eyebrow">{latest.no} · {latest.location}</span>
        </div>

        <div className="home-latest">
          <div className="home-latest__art">
            {latest.heroImage ? (
              <figure className="lg-hero-photo lg-hero-photo--inline">
                <img src={latest.heroImage} alt={latest.title || ""} />
              </figure>
            ) : (
              <TapedPhoto caption={latest.photoCaption} ratio="4 / 3" />
            )}
          </div>
          <div className="home-latest__body">
            <h2 className="display" style={{ fontSize: 'clamp(40px, 5vw, 72px)', lineHeight: 1, margin: 0 }}>
              {latest.title}
            </h2>
            <div style={{ marginTop: 18, marginBottom: 24 }}>
              <FieldLine label="Date" value={latest.date} />
              <FieldLine label="Loc." value={latest.location} />
              <FieldLine label="Wx." value={latest.weather} />
            </div>
            <p className="serif" style={{ fontStyle: 'italic', fontSize: 22, color: 'var(--ink)', lineHeight: 1.55, margin: 0 }}>
              "{latest.excerpt}"
            </p>
            <div style={{ marginTop: 32, display: 'flex', gap: 14, flexWrap: 'wrap' }}>
              <button className="btn" onClick={() => go("note:" + latest.id)}>Read this entry →</button>
              <button className="btn btn--ghost" onClick={() => go("notes")}>All Goat Notes</button>
            </div>
          </div>
        </div>
      </section>

      <hr className="rule rule--double" style={{ margin: '0 32px' }} />

      {/* THREE DOORS ====================================== */}
      <section className="container" style={{ paddingTop: 100, paddingBottom: 120 }}>
        <div className="home-doors">
          {[
          { id: "desk", label: "The Field Desk", sub: "Sit down. Read. Sketch. File an entry by lamplight.", sk: "kettle" },
          { id: "notes", label: "Goat Notes", sub: "Dispatches from West Texas back roads. Filed slowly. Every word meant.", sk: "map" },
          { id: "manifesto", label: "The Manifesto", sub: "A signal, not a brand. Read at your own pace.", sk: "compass" }].
          map((d, i) =>
          <button key={d.id} className="door" onClick={() => go(d.id)}>
              <span className="door__num">{String(i + 1).padStart(2, '0')}</span>
              <span className="door__sketch"><Sketch kind={d.sk} height={120} /></span>
              <span className="door__label display">{d.label}</span>
              <span className="door__sub serif">{d.sub}</span>
              <span className="door__chev hand">go in →</span>
            </button>
          )}
        </div>
      </section>

      {/* QUIET FOOTER NOTE =============================== */}
      <section className="container--narrow" style={{ paddingTop: 40, paddingBottom: 96, textAlign: 'center' }}>
        <p className="hand" style={{ fontSize: 28, color: 'var(--ink)', lineHeight: 1.4 }}>
          Lonesome Goat is not about escaping life.<br />
          It is about <em style={{ color: 'var(--gold-deep)' }}>returning to it.</em>
        </p>
        <div style={{ marginTop: 24 }}>
          <SignOff size={42} />
        </div>
      </section>
    </main>);

}

window.Home = Home;