/* ═══════════════════════════════════════════════════════════
   CircleThrice — sections A: Today · Calendar · Planner
═══════════════════════════════════════════════════════════ */
const CTa = window.CT;

/* ════════════════ TODAY ════════════════ */
function TodaySection({ onOpenBlog, onNav, onToast }) {
  const a = CTa.AUSPICE;
  const featured = CTa.BLOG[0];
  const transits = (CTa.WEEK_EVENTS.find(d => d.today) || {}).events || [];
  const aldebaran = CTa.BLOG.find(b => b.id === 'aldebaran');

  return (
    <div className="fade-in">

      {/* The day, packaged as one object */}
      <div className="block">
        <div className="day-sheet">

          {/* Top bar — date, ruler of the day, day nav */}
          <div className="ds-topbar">
            <div className="ds-topbar-left">
              <span className="ds-date">Today · Saturday 13 June 2026</span>
              <span className="ds-ruler">{a.ruler}<Icon id={a.rulerGlyph} className="p-icon-sm" /> Ruler</span>
            </div>
            <button className="day-nav" onClick={() => onToast && onToast('Tomorrow\'s auspice publishes at midnight.')}>Tomorrow →</button>
          </div>

          {/* Masthead — copy left, sparkline right (stacks on mobile) */}
          <div className="ds-masthead">
            <div className="dm-copy">
              <h1 className="ds-title">Be sovereign in what you do NOT do</h1>
              <p className="ds-desc">Saturday falls under Saturn, ruler of limits and time, so today's magic is subtractive: its strength is in restraint and the deliberate no. Venus enters Leo at dawn and the Moon meets royal Aldebaran tonight — integrity is favored and shortcuts are not. Good for boundary-setting, ending what has run its course, protecting your time, and saying the hard no.</p>
            </div>
            <div className="dm-spark">
              <AuspiceNotch value={a.rating} max={a.max} />
            </div>
          </div>

          {/* Today's exact transits */}
          <div className="ds-region">
            <div className="ds-label" style={{ fontSize: 13, color: 'var(--ink)', letterSpacing: '.16em', marginBottom: 16 }}>Today's Transits · Exact Timing</div>
            <div className="ds-transits">
              {transits.map((e, j) => (
                <div key={j} className="transit-card">
                  <div className="tc-head">
                    <span className="tc-icns">
                      <Icon id={e.glyph} className="tc-pi" />
                      {e.sign && <Icon id={e.sign} className="tc-sign" />}
                      {e.star && (
                        <svg className="tc-star" viewBox="0 0 16 16" aria-hidden="true">
                          <path d="M8 1 L9.2 6.8 L15 8 L9.2 9.2 L8 15 L6.8 9.2 L1 8 L6.8 6.8 Z" fill="currentColor" />
                        </svg>
                      )}
                    </span>
                    <span className="tc-name">{e.name}</span>
                  </div>
                  <div className="tc-meta">
                    <div className="tc-row"><span className="tc-label">Span</span><span className="tc-val">{e.span} <span className="tc-dur">· {e.duration}</span></span></div>
                    <div className="tc-row"><span className="tc-label">Most potent at</span><span className="tc-val">{e.potent}</span></div>
                  </div>
                  <p className="tc-desc">{e.desc}</p>
                </div>
              ))}
            </div>
          </div>

          {/* Go deeper — compact related links */}
          <div className="ds-region ds-deeper">
            <div className="ds-label">Go Deeper</div>
            <div className="ds-links">
              <button className="ds-link" onClick={() => onNav('planner')}>
                <span className="ds-link-kick">Monthly Guide</span>
                <span className="ds-link-title">June 2026 Guide</span>
                <span className="ds-link-arr">→</span>
              </button>
              {aldebaran && (
                <button className="ds-link" onClick={() => onOpenBlog(aldebaran)}>
                  <span className="ds-link-kick">From the Almanac</span>
                  <span className="ds-link-title">{aldebaran.title}</span>
                  <span className="ds-link-arr">→</span>
                </button>
              )}
            </div>
          </div>

        </div>
      </div>

      {/* Week mood strip */}
      <div className="block">
        <div className="sec-label">This Week's Mood · Jun 13–19</div>
        <div className="mood-strip">
          {CTa.WEEK_MOOD.map((d, i) => (
            <div key={i} className={'mood-cell' + (d.today ? ' is-today' : '')}>
              <div className="mood-dow">{d.dow}</div>
              <div className="mood-date">{d.date}</div>
              <div className="mood-word">{d.word}</div>
              <div className="mood-bar">
                {Array.from({ length: 5 }).map((_, j) => (
                  <span key={j} className={'mood-tick' + (j < d.mood ? ' on' : '')}></span>
                ))}
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Featured blog */}
      <div className="block">
        <div className="sec-label">From the Almanac</div>
        <div className="card clickable accent" onClick={() => onOpenBlog(featured)}>
          <div className="card-meta" style={{ marginBottom: 10 }}>{featured.date} · {featured.author}</div>
          <div className="card-title" style={{ fontSize: 24 }}>{featured.title}</div>
          <p className="card-desc" style={{ fontSize: 16.5 }}>{featured.excerpt}</p>
          <div className="mt14">
            <span className="btn-text">Read the post →</span>
          </div>
        </div>
      </div>

      {/* Gentle cross-sell (Planning has full access; this points deeper, not a lock) */}
      <div className="block">
        <UpgradeStrip
          tier="engagement"
          head="Go deeper with Engagement"
          sub="Advanced lunation practice, modular ritual frameworks, and the Venture Strategy workshop unlock at the Engagement tier."
        />
      </div>
    </div>
  );
}

/* ════════════════ CALENDAR ════════════════ */
function CalendarSection() {
  const [view, setView] = useState('week');          // 'week' | 'grid'
  const [sel, setSel] = useState(null);              // {month, day}

  return (
    <div className="fade-in">
      <PageHead
        glyph="p-saturn"
        kicker="Calendar · Astrological Events"
        title="The sky, on schedule"
        desc="Plan against the transits — this week in close detail, or the whole month at a glance."
      />

      <div className="tab-toggle">
        <button className={view === 'week' ? 'active' : ''} onClick={() => setView('week')}>This Week</button>
        <button className={view === 'grid' ? 'active' : ''} onClick={() => setView('grid')}>Month Grid</button>
      </div>

      {view === 'week' ? (
        <div className="block fade-in">
          <div className="sec-label">Saturday 13 — Friday 19 June</div>
          {CTa.WEEK_EVENTS.map((day, i) => (
            <div key={i} className={'week-day' + (day.today ? ' is-today' : '')}>
              <div>
                <div className="wd-dow">{day.dow}</div>
                <div className="wd-num">{day.date}</div>
                {day.today && <span className="wd-today-tag">Today</span>}
              </div>
              <div>
                {day.events.length === 0 ? (
                  <div className="wd-empty">No notable transits.</div>
                ) : day.events.map((e, j) => (
                  <div key={j} className="event-row">
                    <span className="event-icn"><Icon id={e.glyph} /></span>
                    <div className="event-body">
                      <div className="row between" style={{ gap: 12, alignItems: 'baseline' }}>
                        <span className="event-name">{e.name}</span>
                        <span className="event-time">{e.time}</span>
                      </div>
                      <div className="event-desc">{e.desc}</div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          ))}
        </div>
      ) : (
        <div className="block fade-in">
          <div className="sec-label">Tap a marked day for its events</div>
          <div className="month-grids single">
            {CTa.MONTHS.filter(m => m.key === 'jun').map(m => (
              <MonthGrid key={m.key} month={m} sel={sel} setSel={setSel} />
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

function MonthGrid({ month, sel, setSel }) {
  const DOW = ['S', 'M', 'T', 'W', 'T', 'F', 'S'];
  const cells = [];
  for (let i = 0; i < month.firstDow; i++) cells.push(null);
  for (let d = 1; d <= month.days; d++) cells.push(d);
  const selected = sel && sel.key === month.key ? sel.day : null;
  const selEvent = selected ? month.events[selected] : null;

  return (
    <div className="month-block">
      <div className="month-title">{month.name}</div>
      <div className="month-dow-row">
        {DOW.map((d, i) => <div key={i} className="month-dow">{d}</div>)}
      </div>
      <div className="month-grid">
        {cells.map((d, i) => {
          if (d === null) return <div key={i} className="mg-cell empty"></div>;
          const ev = month.events[d];
          const isToday = month.today === d;
          const isSel = selected === d;
          return (
            <div key={i}
              className={'mg-cell' + (ev ? ' has-event' : '') + (isToday ? ' is-today' : '') + (isSel ? ' mg-selected' : '')}
              onClick={() => ev && setSel(isSel ? null : { key: month.key, day: d })}>
              <span className="mg-num">{d}</span>
              {ev && <span className="mg-event-icn"><Icon id={ev.glyph} /></span>}
            </div>
          );
        })}
      </div>
      {selEvent && (
        <div className="month-event-detail fade-in">
          <div className="row between" style={{ gap: 12, alignItems: 'baseline', marginBottom: 5 }}>
            <span className="event-name" style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <Icon id={selEvent.glyph} className="p-icon-sm" />{selEvent.name}
            </span>
            <span className="event-time">{month.name.split(' ')[0]} {sel.day} · {selEvent.time}</span>
          </div>
          <div className="event-desc">{selEvent.desc}</div>
        </div>
      )}
    </div>
  );
}

/* ════════════════ PLANNER ════════════════ */
function PlannerSection({ onToast }) {
  const [month, setMonth] = useState(CTa.PLANNER_MONTHS[0]);
  const suites = CTa.SUITE[month];

  return (
    <div className="fade-in">
      <PageHead
        glyph="p-jupiter"
        kicker="Planner · Monthly Ritual Suite"
        title="Plan the month"
        desc="Each month, a matched set of working documents — a scheduler, a journal, and Ivy's astrological guide. Yours to download as a Planning member."
      />

      <Dropdown value={month} options={CTa.PLANNER_MONTHS} onChange={setMonth} ariaLabel="Select month" />

      <div className="suite-grid">
        {suites.map((s, i) => {
          const isCal = s.type === 'Scheduler';
          return (
          <div key={i} className="card accent suite-card fade-in">
            <div className="suite-icn">
              {s.type === 'Scheduler' && (
                <svg viewBox="0 0 24 24" aria-hidden="true"><rect x="3" y="5" width="18" height="16" rx="2" fill="none" stroke="currentColor" strokeWidth="1.5"/><line x1="3" y1="9.5" x2="21" y2="9.5" stroke="currentColor" strokeWidth="1.5"/><line x1="8" y1="3" x2="8" y2="6" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/><line x1="16" y1="3" x2="16" y2="6" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>
              )}
              {s.type === 'Journal' && (
                <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M6 3 h11 a1 1 0 0 1 1 1 v17 l-3-2 -3 2 -3-2 -3 2 V4 a1 1 0 0 1 1-1 Z" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round"/><line x1="9" y1="8" x2="15" y2="8" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/><line x1="9" y1="11.5" x2="15" y2="11.5" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/></svg>
              )}
              {s.type === 'Guide' && (
                <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 6.5 C9.5 4.5 5.5 4.5 3.5 5.5 v13 c2-1 6-1 8.5 1 2.5-2 6.5-2 8.5-1 v-13 c-2-1-6-1-8.5 1 Z" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round"/><line x1="12" y1="7.5" x2="12" y2="20.5" stroke="currentColor" strokeWidth="1.3"/></svg>
              )}
            </div>
            <div className="card-title" style={{ fontSize: 22 }}>{s.type}</div>
            <p className="card-desc">{s.desc}</p>
            {isCal && (
              <div className="suite-note">
                A calendar file (.ics) — the month's transits and key days drop straight into Apple, Google, or Outlook.
                <button className="suite-note-link" onClick={() => onToast('Opening calendar-setup instructions.')}>How to add it to your calendar →</button>
              </div>
            )}
            <div className="suite-foot">
              <div className="lib-badges"><TierBadge tier="planning" /><TypeBadge type={isCal ? 'ICS' : 'PDF'} /></div>
              <button className="btn btn-ghost btn-block" onClick={() => onToast(isCal ? '<strong>Scheduler</strong> (.ics) for ' + month + ' is downloading — open it to add the month to your calendar.' : '<strong>' + s.type + '</strong> for ' + month + ' is downloading.')}>
                {isCal ? 'Add to Calendar' : 'Download'}
              </button>
            </div>
          </div>
          );
        })}
      </div>
    </div>
  );
}

Object.assign(window, { TodaySection, CalendarSection, PlannerSection, MonthGrid });
