/* Single continuous surface — Home content + (when active) the chat thread below it */
const { useEffect: useEffectS, useRef: useRefS } = React;

function ContentTile({ c, badge }) {
  const D = window.HS_DATA;
  return (
    <div className="tile" onClick={() => window.__openPlayer(c)}>
      <div className="tile-art">
        <img src={c.img} alt="" />
        {badge && <span className="tile-badge">{badge}</span>}
        <button className="tile-over" aria-label="More" onClick={(e) => e.stopPropagation()}>
          <Icon name="overflow" size={18} />
        </button>
      </div>
      <div className="tile-body">
        <div className="t-title">{c.title}</div>
        <div className="t-meta">{c.cat} · {c.len}</div>
      </div>
    </div>
  );
}

/* Horizontal "Based on your needs" card — 72px image left, title right,
   on a tonal backgroundStrong surface (no border) per the Headspace spec */
function NeedCard({ c, label, art, changed, onOpen }) {
  const R = window.__resources || {};
  const src = art ? (R['assets/cards/' + art] || ('assets/cards/' + art)) : c.img;
  return (
    <button className={"need-card" + (changed ? " changed" : "")} onClick={() => onOpen(c)}>
      {changed && <span className="need-newdot" aria-label="Updated for you"></span>}
      <span className="need-art"><img src={src} alt="" /></span>
      <span className="need-title hs-label-sm">{label || c.title}</span>
    </button>
  );
}

function RecCard({ c, onOpen }) {
  const D = window.HS_DATA;
  return (
    <div className="rec-card" onClick={() => onOpen(c)}>
      <div className="rec-art"><img src={c.img} alt="" /></div>
      <div className="rec-info">
        <div className="r-title">{c.title}</div>
        <div className="r-meta">{c.cat} · {c.teacher} · {c.len}</div>
      </div>
      <span className="rec-play"><Icon name="play" size={18} color="#fff" /></span>
    </div>
  );
}
window.RecCard = RecCard;

function EbbActions() {
  const [v, setV] = React.useState(0);
  const [copied, setCopied] = React.useState(false);
  return (
    <div className="msg-actions">
      <button aria-label="Copy" className={copied ? "on" : ""}
        onClick={() => { setCopied(true); window.setTimeout(() => setCopied(false), 1200); }}>
        <Icon name={copied ? "send" : "copy"} size={17} />
      </button>
      <button className={v === 1 ? "on" : ""} aria-label="Helpful" onClick={() => setV(v === 1 ? 0 : 1)}><Icon name="thumbs-up" size={17} /></button>
      <button className={v === -1 ? "on" : ""} aria-label="Not helpful" onClick={() => setV(v === -1 ? 0 : -1)}><Icon name="thumbs-down" size={17} /></button>
    </div>
  );
}
window.EbbActions = EbbActions;

/* Card Stack — a vertical carousel. Every card is ONE persistent element
   that eases between its "peek" state (grey bar with dot + title) and the
   "active" state (full art card), so tapping morphs between states instead
   of swapping elements. The active card holds a constant position; the
   module keeps a fixed height so nothing else on the page moves. */
function CardStack({ cards, onOpen, initialActive }) {
  const [active, setActive] = React.useState(initialActive || 0);
  const [drag, setDrag] = React.useState(0);      // live vertical drag offset (px)
  const [dragging, setDragging] = React.useState(false);
  const st = React.useRef({ down: false, startY: 0, moved: false, idx: 0, dy: 0 });

  const go = (idx) => { if (idx >= 0 && idx < cards.length) setActive(idx); };

  const onDown = (e, idx) => {
    st.current = { down: true, startY: e.clientY, moved: false, idx, dy: 0 };
    setDragging(true);
    try { e.currentTarget.setPointerCapture(e.pointerId); } catch (_) {}
  };
  const onMove = (e) => {
    if (!st.current.down) return;
    let dy = e.clientY - st.current.startY;
    if (Math.abs(dy) > 4) st.current.moved = true;
    // rubber-band resistance at the ends of the stack
    if ((active === 0 && dy > 0) || (active === cards.length - 1 && dy < 0)) dy *= 0.32;
    st.current.dy = dy;
    setDrag(dy);
  };
  const onUp = () => {
    if (!st.current.down) return;
    st.current.down = false;
    setDragging(false);
    const dy = st.current.dy;
    setDrag(0);
    const TH = 44;
    if (st.current.moved && Math.abs(dy) > TH) {
      go(active + (dy < 0 ? 1 : -1)); // drag up → next, down → previous
    } else if (!st.current.moved) {
      const idx = st.current.idx;
      if (idx === active) onOpen(cards[idx].play); else go(idx);
    }
  };

  const R = (window.__resources || {});
  const art = (f) => R['assets/cards/' + f] || ('assets/cards/' + f);

  // Top-anchored accordion: top card always at y=0; active expands in place.
  // Collapsed cards extend past their visible band and tuck under the next card
  // with a square (tucked) edge, so it reads as physically stacked cards.
  // OVL = COL - STEP keeps every overlap the same depth. Constant height.
  const EXP = 214, STEP = 44, COL = 66, OVL = COL - STEP;
  let y = 0;
  const lay = cards.map((c, i) => {
    const top = y;
    const isActive = i === active;
    y += isActive ? (EXP - OVL) : STEP;
    return { top, isActive, dist: Math.abs(i - active) };
  });
  const vpH = (EXP - OVL) + Math.max(0, cards.length - 2) * STEP + COL;

  return (
    <div className="cstack">
      <div className="cstack-vp" style={{ height: vpH }}>
        {cards.map((c, idx) => {
          const L = lay[idx];
          const inset = L.isActive ? 0 : Math.min(L.dist, 3) * 8;
          const style = {
            backgroundImage: 'url(' + art(c.art) + ')',
            top: L.top, height: L.isActive ? EXP : COL,
            left: inset, right: inset,
            zIndex: L.isActive ? 40 : 30 - Math.min(L.dist, 3) * 6,
          };
          if (L.isActive && dragging && drag) style.transform = 'translateY(' + drag + 'px)';
          const dirClass = L.isActive ? "is-active" : ("is-collapsed " + (idx < active ? "is-above" : "is-below"));
          return (
            <button key={c.id} className={"stack-card " + dirClass + (L.isActive && dragging ? " dragging" : "")}
              style={style}
              onPointerDown={(e) => onDown(e, idx)}
              onPointerMove={onMove}
              onPointerUp={onUp}
              onPointerCancel={onUp}>
              <span className="sc-grey"></span>
              <span className="sc-scrim"></span>
              <span className="sc-dot"></span>
              <span className="sc-full">
                <span className="stack-pill hs-label-xs">{c.pill}</span>
                <span className="stack-title hs-heading-md">{c.title}</span>
                <span className="stack-desc hs-body-xs">{c.desc}</span>
                <span className="stack-meta">
                  <Icon name={c.metaIcon || 'audio'} size={16} color="#fff" />
                  <span className="hs-label-sm">{c.cat} · {c.len}</span>
                </span>
              </span>
              <span className="sc-peek">
                <span className="peek-dot"></span>
                <span className="peek-t hs-label-sm">{c.title}</span>
              </span>
              {c.changed && <span className="sc-newdot" aria-hidden="true"></span>}
            </button>
          );
        })}
      </div>

      <div className="cstack-rail" aria-hidden="true">
        {cards.map((_, i) => (
          <span key={i} className={"rail-dot" + (i === active ? " on" : "")}></span>
        ))}
      </div>
    </div>
  );
}

const TOD_OPTIONS = [['morning', 'Morning'], ['afternoon', 'Afternoon'], ['night', 'Night']];

function MainScreen({ onOpenPlayer, period, setPeriod, personalized, updated }) {
  const D = window.HS_DATA;
  window.__openPlayer = onOpenPlayer;
  const F = D.FEATURE;
  const [menuOpen, setMenuOpen] = React.useState(false);

  const CFGS = {
    morning: {
      word: 'morning',
      sub: "Let's get grounded before the day gets loud.",
      meta: 'Slept 7h 10m',
      stack: [
        { id: 'm1', title: 'Own your morning', pill: 'Powered by Oura™', desc: "Even if sleep didn't come easily last night, a morning pick-me-up can jump start your day.", cat: 'Meditation', len: '4 min', metaIcon: 'audio', art: 'green-sparkle.png', play: D.C.gratitude },
        { id: 'm2', title: 'Give yourself some grace', pill: 'For this moment', desc: "We can't always be perfect, and that's okay. Remind yourself that you have good intentions.", cat: 'Advice', len: '7 min', metaIcon: 'play', art: 'calm-leaf.png', play: D.C.compassion },
        { id: 'm3', title: 'Turn criticism into growth', pill: 'A gentle reframe', desc: 'Notice the harsh inner voice, and try meeting it with a little more understanding.', cat: 'Meditation', len: '6 min', metaIcon: 'audio', art: 'warm-flower.png', play: D.C.reframe },
        { id: 'm4', title: 'Learn the Basics of Meditation', pill: 'Popular right now', desc: 'Other members are loving this course to learn how to meditate. Try it at your own pace.', cat: 'Course', len: 'Session 1 of 10', metaIcon: 'audio', art: 'sun-smile.png', play: D.C.galloping },
      ],
      tiles: [{ c: D.C.grounded, label: 'Basics', art: 'basics.png' }, { c: D.C.letgo, label: 'Balance', art: 'balance.jpg' }],
      chips: ["I'm feeling stressed", "Help me focus", "I can't sleep"],
    },
    afternoon: {
      word: 'afternoon',
      sub: "Let's steady the middle of the day before it runs away.",
      meta: '5,240 steps so far',
      stack: [
        { id: 'a1', title: 'Reset your focus', pill: 'For the afternoon slump', desc: 'A short reset to clear the noise and get back into the zone.', cat: 'Meditation', len: '5 min', art: 'green-sparkle.png', play: D.C.focus },
        { id: 'a2', title: 'Come back to now', pill: 'A quick pause', desc: 'Step out of the rush for a moment and land back in your body.', cat: 'Reflect', len: '3 min', art: 'calm-leaf.png', play: D.C.pauseEbb },
        { id: 'a3', title: 'Loosen the tension', pill: 'Midday unwind', desc: 'Release the tightness you’ve been holding in your shoulders.', cat: 'Meditation', len: '4 min', art: 'warm-flower.png', play: D.C.reframe },
      ],
      tiles: [{ c: D.C.focus, label: 'Deep focus' }, { c: D.C.reframe, label: 'Reset' }],
      chips: ["I need to refocus", "I'm overwhelmed", "Help me reset"],
    },
    night: {
      word: 'evening',
      sub: "Let's wind down and let the day go.",
      meta: 'Resting HR 58 bpm',
      stack: [
        { id: 'n1', title: 'Wind down for sleep', pill: 'For a restful night', desc: 'Drift toward rest with a slow, quiet wind-down before bed.', cat: 'Sleepcast', len: '20 min', art: 'calm-leaf.png', play: D.C.sleep },
        { id: 'n2', title: 'Let the day go', pill: 'Release the day', desc: 'Set down what you’re still carrying, one slow breath at a time.', cat: 'Meditation', len: '5 min', art: 'green-sparkle.png', play: D.C.deepbreaths },
        { id: 'n3', title: 'Meet yourself kindly', pill: 'A soft landing', desc: 'A short pause to close the day with a little more kindness.', cat: 'Meditation', len: '5 min', art: 'sun-smile.png', play: D.C.compassion },
      ],
      tiles: [{ c: D.C.sleep, label: 'Sleep' }, { c: D.C.compassion, label: 'Kindness' }],
      chips: ["I can't switch off", "Help me sleep", "My mind is racing"],
    },
  };
  const cfg = CFGS[period] || CFGS.morning;
  let tiles = cfg.tiles;
  let stack = cfg.stack;
  const chips = cfg.chips;

  // Flow 1 — after the Ebb conversation, "Adjusting your plan…" swaps the feed:
  // the second stack card is surfaced and a new "needs" card appears, each with
  // a primary-blue "new" dot.
  if (updated) {
    stack = cfg.stack.map((c, i) => (i === 1 ? { ...c, changed: true } : c));
    tiles = [
      { c: (cfg.tiles[0] || {}).c || D.C.grounded, label: 'Basics', art: (cfg.tiles[0] || {}).art },
      { c: D.C.grounded, label: 'Spacial tense relief', art: 'spatial.png', changed: true },
    ];
  } else if (personalized) {
    stack = [
      { id: 'pz1', title: 'Unwind a racing mind', pill: 'Personalized for you', desc: "You mentioned your head won't switch off at night — here's a wind-down shaped around that.", cat: 'Meditation', len: '8 min', metaIcon: 'audio', art: 'racing-mind.png', play: D.C.reframe, changed: true },
      ...cfg.stack.slice(0, 3),
    ];
    tiles = [
      { c: D.C.sleep, label: 'Sleep', art: (cfg.tiles[0] || {}).art, changed: true },
      cfg.tiles[1] || cfg.tiles[0],
    ];
  }

  return (
    <div className="scroll">
      <div className="home-pad">
        <div className="greeting">
          <h1 className="greeting-h1">
            <span className="g-light">Good</span> <span className="tod-word">{cfg.word}</span>
            <button className={"tod-toggle" + (menuOpen ? " open" : "")} aria-label="Change time of day"
              onClick={(e) => { e.stopPropagation(); setMenuOpen((o) => !o); }}>
              <span className="tod-caret"><Icon name={menuOpen ? "sort-up" : "sort-down"} size={20} /></span>
            </button>
            <br />Blake
          </h1>
          {menuOpen && (
            <React.Fragment>
              <div className="tod-scrim" onClick={() => setMenuOpen(false)}></div>
              <div className="tod-menu">
                {TOD_OPTIONS.map(([k, label]) => (
                  <button key={k} className={"tod-item" + (period === k ? " active" : "")}
                    onClick={() => { setPeriod(k); setMenuOpen(false); }}>
                    <span>{label}</span>
                    {period === k && <span className="tod-check"><Icon name="check" size={20} /></span>}
                  </button>
                ))}
              </div>
            </React.Fragment>
          )}
        </div>

        <CardStack key={period + (updated ? '-u' : '')} cards={stack} initialActive={updated ? 1 : 0} onOpen={onOpenPlayer} />

        <div className="sec-head needs-head">
          <h2 className="hs-heading-sm">Based on your needs</h2>
          <span className="needs-spark"><Icon name="ai" size={18} /></span>
        </div>
        <div className="needs">
          {tiles.map((t, i) => <NeedCard key={i} c={t.c} label={t.label} art={t.art} changed={t.changed} onOpen={onOpenPlayer} />)}
        </div>
      </div>
    </div>
  );
}
window.MainScreen = MainScreen;
