// Card Draw v4 — perched raven center, season-image card backs, proper flow:
// Page load -> 4 face-down cards + perched raven center. NO question panel.
// Click a card OR "Let the Raven Choose" -> question appears below.

const { useState: useStateC4, useEffect: useEffectC4, useRef: useRefC4 } = React;

const DRAW_STATE_KEY_V4 = 'up_v4_draw_state';

function dayKeyV4() {
  const d = new Date();
  return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`;
}
function loadDrawV4() {
  try { return JSON.parse(localStorage.getItem(DRAW_STATE_KEY_V4) || 'null'); }
  catch { return null; }
}
function saveDrawV4(s) {
  try { localStorage.setItem(DRAW_STATE_KEY_V4, JSON.stringify(s)); } catch {}
}

function CardDrawV4() {
  const PILLARS = window.PILLARS_V4;
  const BLESSINGS = window.BLESSINGS_V4;
  const ToolIcon = window.ToolIconV4;

  // Phases: 'idle' | 'shuffling' | 'revealed' | 'already'
  const [phase, setPhase] = useStateC4('idle');
  const [chosenIdx, setChosenIdx] = useStateC4(null);
  const [order, setOrder] = useStateC4([0, 1, 2, 3]);
  const [questionIdx, setQuestionIdx] = useStateC4(0);
  const [blessingIdx, setBlessingIdx] = useStateC4(0);
  const [activeTool, setActiveTool] = useStateC4(null);
  const revealRef = useRefC4(null);

  // Default state: ALWAYS show the cards on page load.
  // The daily lock no longer auto-restores the previous reveal —
  // it only prevents losing the draw if the user reloads after picking.
  // (Removed the auto-jump to 'already' that was breaking the initial view.)

  const chosenPillar = chosenIdx !== null ? PILLARS[order[chosenIdx]] : null;

  const ravenChoose = () => {
    const newOrder = [0,1,2,3].sort(() => Math.random() - 0.5);
    setOrder(newOrder);
    setActiveTool(null);
    setPhase('shuffling');
    setTimeout(() => {
      const idx = Math.floor(Math.random() * 4);
      setChosenIdx(idx);
      setTimeout(() => completeDraw(newOrder, idx), 500);
    }, 1100);
  };

  const pickCard = (idx) => {
    if (phase !== 'idle') return;
    setActiveTool(null);
    setChosenIdx(idx);
    setTimeout(() => completeDraw(order, idx), 500);
  };

  const completeDraw = (orderArr, idx) => {
    const pillar = PILLARS[orderArr[idx]];
    const qIdx = Math.floor(Math.random() * pillar.questions.length);
    const bIdx = Math.floor(Math.random() * BLESSINGS.length);
    setQuestionIdx(qIdx);
    setBlessingIdx(bIdx);
    setPhase('revealed');
    saveDrawV4({
      day: dayKeyV4(),
      order: orderArr,
      chosenIdx: idx,
      questionIdx: qIdx,
      blessingIdx: bIdx
    });
    setTimeout(() => {
      if (revealRef.current) {
        const top = revealRef.current.getBoundingClientRect().top + window.scrollY - 90;
        window.scrollTo({ top, behavior: 'smooth' });
      }
    }, 600);
  };

  const drawAnother = () => {
    try { localStorage.removeItem(DRAW_STATE_KEY_V4); } catch {}
    setChosenIdx(null);
    setActiveTool(null);
    setOrder([0,1,2,3].sort(() => Math.random() - 0.5));
    setPhase('idle');
    // Scroll back up to the cards
    setTimeout(() => {
      const drawEl = document.getElementById('draw');
      if (drawEl) {
        const top = drawEl.getBoundingClientRect().top + window.scrollY - 80;
        window.scrollTo({ top, behavior: 'smooth' });
      }
    }, 200);
  };

  const isCardsView = phase === 'idle' || phase === 'shuffling';

  return (
    <div className="container draw-section">
      <div className="section-label smallcaps">The Card Draw</div>
      <div className="section-title-wrap">
        <h2 className="section-title" data-section-title>Begin Your Pathway</h2>
      </div>
      <p className="section-sub">
        Four cards. One season. One question for today.<br/>
        The card you draw is the one you need.
      </p>

      {/* CARDS VIEW — always shown until a card is chosen */}
      {isCardsView && (
        <>
          <div className="draw-controls-top">
            <div className="draw-prompt">
              Reach for the card that calls to you — <span className="accent">or let the raven choose for you</span>.
            </div>
            <button className="btn solid" onClick={ravenChoose} disabled={phase === 'shuffling'}>
              {phase === 'shuffling' ? 'Drawing…' : 'Let the Raven Choose'}
            </button>
            <div className="draw-or">Or pick a card below</div>
          </div>

          <div className="draw-stage-v2">
            {/* Perched raven in center */}
            <img
              src="assets/raven.png"
              alt=""
              className="draw-center-raven"
            />
            <div className="draw-grid">
              {[0,1,2,3].map((pos) => {
                const pillar = PILLARS[order[pos]];
                const isChosen = chosenIdx === pos;
                const isDim = chosenIdx !== null && !isChosen;
                const cls = [
                  'qcard',
                  phase === 'shuffling' ? 'shuffling' : '',
                  isDim ? 'dim' : ''
                ].filter(Boolean).join(' ');
                return (
                  <div
                    key={pos}
                    className={cls}
                    style={{ ['--accent']: pillar.accent, animationDelay: `${pos * 0.1}s` }}
                    onClick={() => pickCard(pos)}
                  >
                    <div className="qcard-inner">
                      <img className="qcard-season-img" src={pillar.cardImage} alt="" />
                      <div className="qcard-vignette"></div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </>
      )}

      {/* REVEAL VIEW — only after a card is picked */}
      {(phase === 'revealed' || phase === 'already') && chosenPillar && (
        <RevealPanelV4
          pillar={chosenPillar}
          question={chosenPillar.questions[questionIdx]}
          blessing={BLESSINGS[blessingIdx]}
          isReturning={phase === 'already'}
          activeTool={activeTool}
          setActiveTool={setActiveTool}
          drawAnother={drawAnother}
          revealRef={revealRef}
          ToolIcon={ToolIcon}
        />
      )}
    </div>
  );
}

function RevealPanelV4({ pillar, question, blessing, isReturning, activeTool, setActiveTool, drawAnother, revealRef, ToolIcon }) {
  return (
    <div ref={revealRef} className="reveal-v3 show" style={{ ['--accent']: pillar.accent }}>
      <div className="reveal-v3-inner">
        {isReturning && (
          <div style={{
            textAlign: 'center',
            fontFamily: "'Cormorant Garamond', serif",
            fontStyle: 'italic',
            color: 'var(--ink-mute)',
            fontSize: 15,
            marginBottom: 24,
            paddingBottom: 16,
            borderBottom: '1px solid var(--line-soft)'
          }}>
            You drew this card today. Sit with it again — or draw another if you must.
          </div>
        )}

        {/* Small season image at top of reveal */}
        <div className="reveal-card-thumb">
          <img src={pillar.cardImage} alt="" />
        </div>

        <div className="reveal-season">{pillar.season} · The Pillar of</div>
        <h3 className="reveal-pillar-title">{pillar.name}</h3>
        <p className="reveal-tagline">{pillar.essence}</p>

        <div className="reveal-question-block">
          <div className="question-label">Your Question Today</div>
          <div className="reveal-question">{question}</div>
          <div className="question-underline"></div>
        </div>

        <div className="tools-label">— A Few Tools for the Sitting —</div>
        <div className="tools-row">
          {['traditional', 'action', 'brave'].map((key) => {
            const tool = pillar.tools[key];
            const isActive = activeTool === key;
            return (
              <ToolCardV4
                key={key}
                kind={key}
                tool={tool}
                isActive={isActive}
                onActivate={() => setActiveTool(isActive ? null : key)}
                ToolIcon={ToolIcon}
              />
            );
          })}
        </div>

        <div className="blessing">
          <div className="blessing-text">"{blessing}"</div>
          <div className="blessing-signoff">— Walk gently —</div>
          <div className="return-tomorrow">
            Come back tomorrow. We go deeper.
            <a href="#" onClick={(e) => { e.preventDefault(); drawAnother(); }}>Draw Another</a>
          </div>
        </div>
      </div>
    </div>
  );
}

function ToolCardV4({ kind, tool, isActive, onActivate, ToolIcon }) {
  const kindLabel = { traditional: 'Quiet', action: 'Present', brave: 'Brave' }[kind];
  return (
    <div className={`tool-card ${isActive ? 'active' : ''}`} onClick={onActivate}>
      <div className="tool-icon"><ToolIcon kind={tool.icon} /></div>
      <div className="tool-kind">{kindLabel}</div>
      <div className="tool-title">{tool.title}</div>
      <div className="tool-body">{tool.body}</div>
      {isActive && <ToolInteractiveV4 tool={tool} />}
    </div>
  );
}

function ToolInteractiveV4({ tool }) {
  if (tool.kind === 'breath') {
    return (
      <div className="tool-action-body">
        <strong>Breathe with the circle</strong>
        <div className="breath-circle"></div>
        <div className="breath-label">in · out · in · out</div>
      </div>
    );
  }
  if (tool.kind === 'timer') return <TimerToolV4 seconds={tool.timer || 60} />;
  if (tool.kind === 'song') {
    return (
      <div className="tool-action-body">
        <strong>Right now</strong>
        Open your music. Choose the song. Turn up the volume. Move with it for the length of the chorus, at least.
      </div>
    );
  }
  if (tool.kind === 'journal') {
    return (
      <div className="tool-action-body">
        <strong>Take this offline</strong>
        Open a notebook or your notes app. Write one sentence longer than feels comfortable. Then close it.
      </div>
    );
  }
  if (tool.kind === 'action' || tool.kind === 'challenge') {
    return (
      <div className="tool-action-body">
        <strong>Today, if you can</strong>
        This will feel slightly too much. That is how you know it is the right one. Do it anyway. Tell no one.
      </div>
    );
  }
  return null;
}

function TimerToolV4({ seconds }) {
  const [remaining, setRemaining] = useStateC4(seconds);
  const [running, setRunning] = useStateC4(false);
  useEffectC4(() => {
    if (!running) return;
    const t = setInterval(() => {
      setRemaining(r => {
        if (r <= 1) { clearInterval(t); setRunning(false); return 0; }
        return r - 1;
      });
    }, 1000);
    return () => clearInterval(t);
  }, [running]);

  const mm = String(Math.floor(remaining / 60)).padStart(2, '0');
  const ss = String(remaining % 60).padStart(2, '0');

  return (
    <div className="tool-action-body" onClick={(e) => e.stopPropagation()}>
      <strong>{remaining === 0 ? 'There you are.' : 'Begin when ready'}</strong>
      <div className="tool-timer">{mm}:{ss}</div>
      <div style={{ textAlign: 'center', marginTop: 10 }}>
        {remaining > 0 && !running && (
          <button className="btn ghost" style={{ fontSize: 10, padding: '8px 16px' }}
            onClick={(e) => { e.stopPropagation(); setRunning(true); }}>Begin</button>
        )}
        {running && <div className="tool-timer-label" style={{ marginTop: 6 }}>· sit with it ·</div>}
        {remaining === 0 && (
          <button className="btn ghost" style={{ fontSize: 10, padding: '8px 16px' }}
            onClick={(e) => { e.stopPropagation(); setRemaining(seconds); }}>Again</button>
        )}
      </div>
    </div>
  );
}

window.CardDrawV4 = CardDrawV4;
