// screens.jsx — HomeScreen + ListScreen

const { useState, useEffect } = React;

// ============================================================ PATCH CONFIG
const PATCHES = {
  'un-plaza':          { icon: 'globe', color: '#4D9DE0' },
  'sf-library':        { icon: 'book',  color: '#38C4BA' },
  'city-hall':         { icon: 'dome',  color: '#C9A842' },
  'fairmont':          { icon: 'key',   color: '#E08C4D' },
  'grace-cathedral':   { icon: 'rose',  color: '#9B7FEA' },
  'opera-house':       { icon: 'lyre',  color: '#E04D7A' },
  'veterans-building': { icon: 'star',  color: '#7FCF7F' },
};

function PatchIcon({ name, size = 18 }) {
  const p = { width: size, height: size, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 1.8, strokeLinecap: "round", strokeLinejoin: "round" };
  switch (name) {
    case 'globe': return <svg {...p}><circle cx="12" cy="12" r="9"/><path d="M3.6 9h16.8M3.6 15h16.8"/><path d="M12 3c-2.8 2.8-4.5 5.7-4.5 9s1.7 6.2 4.5 9"/><path d="M12 3c2.8 2.8 4.5 5.7 4.5 9s-1.7 6.2-4.5 9"/></svg>;
    case 'book':  return <svg {...p}><path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"/><path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"/></svg>;
    case 'dome':  return <svg {...p}><path d="M4 10a8 8 0 0 1 16 0"/><line x1="2" y1="10" x2="22" y2="10"/><line x1="6" y1="10" x2="6" y2="20"/><line x1="18" y1="10" x2="18" y2="20"/><line x1="2" y1="20" x2="22" y2="20"/><line x1="12" y1="4" x2="12" y2="10"/></svg>;
    case 'key':   return <svg {...p}><circle cx="7.5" cy="15.5" r="5.5"/><path d="M21.5 2.5l-9.6 9.6"/><path d="M16 8l2 2"/></svg>;
    case 'rose':  return <svg {...p}><circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="2.5"/><path d="M12 9.5V3M12 14.5V21M14.5 12H21M9.5 12H3M13.77 10.23L18.36 5.64M10.23 13.77L5.64 18.36M13.77 13.77L18.36 18.36M10.23 10.23L5.64 5.64"/></svg>;
    case 'lyre':  return <svg {...p}><path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/></svg>;
    case 'star':  return <svg {...p}><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg>;
    default: return null;
  }
}

function PatchBadge({ stop, size = 40, claimed = false }) {
  const cfg = PATCHES[stop.id] || { icon: 'star', color: '#4D9DE0' };
  return (
    <div
      className={"patch-badge" + (claimed ? " claimed" : "")}
      style={{ '--pc': cfg.color, width: size, height: size }}
    >
      <PatchIcon name={cfg.icon} size={Math.round(size * 0.46)} />
    </div>
  );
}

window.PATCHES    = PATCHES;
window.PatchIcon  = PatchIcon;
window.PatchBadge = PatchBadge;

// ============================================================ COLLECT SOUND
function playCollectSound() {
  try {
    const ctx = new (window.AudioContext || window.webkitAudioContext)();
    const t = ctx.currentTime;
    [[1046.5, 0], [1318.5, 0.09], [1568.0, 0.18]].forEach(([freq, delay]) => {
      const osc = ctx.createOscillator();
      const gain = ctx.createGain();
      osc.connect(gain);
      gain.connect(ctx.destination);
      osc.type = 'sine';
      osc.frequency.value = freq;
      gain.gain.setValueAtTime(0, t + delay);
      gain.gain.linearRampToValueAtTime(0.22, t + delay + 0.015);
      gain.gain.exponentialRampToValueAtTime(0.001, t + delay + 0.5);
      osc.start(t + delay);
      osc.stop(t + delay + 0.52);
    });
  } catch (e) {}
}
window.playCollectSound = playCollectSound;

// ============================================================ ARRIVAL OVERLAY
function ArrivalOverlay({ stop, onCollect, onDismiss, isClaimed }) {
  const [collecting, setCollecting] = useState(false);
  const cfg = PATCHES[stop.id] || { color: '#4D9DE0' };

  useEffect(() => {
    if (collecting) return;
    const t = setTimeout(onDismiss, 6000);
    return () => clearTimeout(t);
  }, [collecting]);

  const handleCollect = () => {
    if (collecting) return;
    playCollectSound();
    setCollecting(true);
    setTimeout(onCollect, 1100);
  };

  return (
    <div className={"arrival-overlay" + (collecting ? " is-collecting" : "")}>
      <div className="arrival-panel">
        <div className="arrival-eyebrow">
          {collecting ? "Patch collected" : "You've arrived"}
        </div>
        <div
          className={"arrival-badge-anim" + (collecting ? " burst" : "")}
          style={{ position: "relative" }}
        >
          <PatchBadge stop={stop} size={88} claimed={true} />
          {collecting && (
            <div className="collect-particles" aria-hidden="true">
              {Array.from({ length: 8 }, (_, i) => {
                const a = (i / 8) * Math.PI * 2;
                return (
                  <div key={i} className="collect-particle"
                    style={{
                      "--dx": Math.cos(a).toFixed(3),
                      "--dy": Math.sin(a).toFixed(3),
                      background: cfg.color,
                    }}
                  />
                );
              })}
            </div>
          )}
        </div>
        <div className="arrival-name">{stop.name}</div>
        <div className="arrival-foot">
          {isClaimed ? (
            <button className="btn focusable" data-autofocus onClick={onDismiss}>
              Continue
            </button>
          ) : (
            <button
              className={"btn primary focusable" + (collecting ? " is-focused" : "")}
              data-autofocus
              onClick={handleCollect}
              style={collecting ? { pointerEvents: "none" } : {}}
            >
              {collecting ? "✓ Collected" : "Collect Patch"}
            </button>
          )}
        </div>
      </div>
    </div>
  );
}
window.ArrivalOverlay = ArrivalOverlay;

function Icon({ name, size = 16 }) {
  const p = {
    width: size, height: size, viewBox: "0 0 24 24", fill: "none",
    stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round"
  };
  switch (name) {
    case "back":    return (<svg {...p}><polyline points="15 18 9 12 15 6" /></svg>);
    case "chevron": return (<svg {...p}><polyline points="9 6 15 12 9 18" /></svg>);
    case "play":    return (<svg {...p}><polygon points="6 4 20 12 6 20" fill="currentColor" stroke="none" /></svg>);
    default: return null;
  }
}

// ============================================================ HOME
function HomeScreen({ onStart }) {
  return (
    <div className="screen" style={{ padding: "40px 42px 30px" }}>
      <div className="bloom home-bloom" />

      <div className="home-hero">
        <div className="home-eyebrow">San Francisco</div>
        <div className="home-headline">UN Charter Trail</div>
        <div className="home-subtitle">Birthplace of the United Nations</div>
      </div>

      <div className="home-foot">
        <button
          className="btn primary focusable"
          data-autofocus
          onClick={onStart}
          style={{ marginTop: 2, padding: "14px 16px", fontSize: 12, letterSpacing: ".18em" }}
        >
          Begin the Trail
        </button>
        <div className="home-disclaimer">
          A self-guided walkathon for the UN's 80th anniversary · Not affiliated with the United Nations
        </div>
      </div>
    </div>
  );
}

// ============================================================ LIST
function ListScreen({ onStop, onBack, userPos, claimed = new Set() }) {
  const nearestId = window.nearestStopId ? window.nearestStopId(userPos) : null;

  return (
    <div className="screen" data-back-on-left data-right-to-back>
      <div className="bloom" style={{ width: 280, height: 150, top: -50, left: 150, opacity: 0.8 }} />

      <div className="stop-list">
        {window.STOPS.map((stop, i) => (
          <div
            key={stop.id}
            className="stop-row focusable"
            data-autofocus={i === 0 ? true : undefined}
            onClick={() => onStop(stop)}
          >
            <PatchBadge stop={stop} size={40} claimed={claimed.has(stop.id)} />
            <div className="stop-info">
              <div className="stop-name-row">
                <div className="stop-name">{stop.name}</div>
                {nearestId === stop.id && <span className="nearest-tag">Nearest</span>}
              </div>
              <div className="stop-sub">{stop.subtitle} · {stop.duration}</div>
            </div>
            <div className="stop-chevron"><Icon name="chevron" size={13} /></div>
          </div>
        ))}
      </div>

      <div style={{ display: "flex", gap: 10, marginTop: 12 }}>
        <button className="btn focusable" data-back onClick={onBack}>
          <Icon name="back" size={14} /> Back
        </button>
      </div>
    </div>
  );
}

window.Icon       = Icon;
window.HomeScreen = HomeScreen;
window.ListScreen = ListScreen;
