/* =====================================================================
   Mereka v2 — My Calendar (full page)
   Month grid + brand-colored event chips + upcoming list.
   Uses DashShell chrome (same sidebar/navbar as the rest of the app).
   ===================================================================== */

const CAL_EVENTS = [
  { d: '2026-07-18', t: 'Tropical Garden Walking Tour', time: '9:00 AM', type: 'Experience', loc: 'Genting Highlands', slug: '/web/experiences/tropical-garden-tour' },
  { d: '2026-07-25', t: 'Traditional Batik Painting Workshop', time: '3:00 PM', type: 'Experience', loc: 'Bangsar, KL', slug: '/web/experiences/kuala-lumpur-batik-workshop' },
  { d: '2026-07-29', t: 'AI Fundamentals · Office Hours', time: '4:00 PM', type: 'Programme', loc: 'Online', slug: '/app/dashboard/programmes' },
  { d: '2026-07-29', t: 'Session with Rafael Tan', time: '6:00 PM', type: 'Expertise', loc: 'Online', slug: '/app/dashboard/chats' },
  { d: '2026-07-30', t: 'UX Audit & Roadmap · Kickoff', time: '11:00 AM', type: 'Expertise', loc: 'Remote', slug: '/web/expertise/ux-audit-roadmap' },
  { d: '2026-07-31', t: 'Brand Identity Sprint · Review', time: '2:00 PM', type: 'Expertise', loc: 'Studio Kuala', slug: '/web/expertise/brand-identity-sprint' },
  { d: '2026-08-02', t: 'Pottery Wheel Throwing', time: '10:00 AM', type: 'Experience', loc: 'Subang Jaya', slug: '/web/experiences/pottery-wheel-throwing' },
  { d: '2026-08-05', t: 'Career Accelerator · Module 5', time: '7:00 PM', type: 'Programme', loc: 'Online', slug: '/app/dashboard/programmes' },
  { d: '2026-08-05', t: 'Content Engine · Check-in', time: '9:00 AM', type: 'Expertise', loc: 'Online', slug: '/web/expertise/content-engine-playbook' },
  { d: '2026-08-08', t: 'Sourdough Bread Baking Class', time: '2:00 PM', type: 'Experience', loc: 'Damansara', slug: '/web/experiences/sourdough-bread-class' },
  { d: '2026-08-12', t: 'Assignment due · Prompt design', time: '11:59 PM', type: 'Deadline', loc: '', slug: '/app/dashboard/courses' },
  { d: '2026-08-15', t: 'Growth Diagnostic · Wrap-up', time: '3:30 PM', type: 'Expertise', loc: 'Remote', slug: '/web/expertise/growth-diagnostic-plan' },
];

const CAL_TYPE = {
  Experience: { chip: 'bg-primary-light text-primary-700', dot: 'bg-primary', label: 'Experience' },
  Expertise: { chip: 'bg-fob-light text-fob', dot: 'bg-fob', label: 'Expertise' },
  Programme: { chip: 'bg-[#EAF0F8] text-support', dot: 'bg-support', label: 'Programme' },
  Deadline: { chip: 'bg-neutral-200 text-ink', dot: 'bg-ink', label: 'Deadline' },
};

function calKey(y, m, d) {
  return `${y}-${String(m + 1).padStart(2, '0')}-${String(d).padStart(2, '0')}`;
}

function UserCalendarPage() {
  const today = new Date();
  const [cy, setCy] = React.useState(today.getFullYear());
  const [cm, setCm] = React.useState(today.getMonth());
  const monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
  const dayNames = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];

  const eventsByDay = {};
  CAL_EVENTS.forEach(e => { (eventsByDay[e.d] = eventsByDay[e.d] || []).push(e); });

  const firstDay = new Date(cy, cm, 1).getDay();
  const startOffset = firstDay === 0 ? 6 : firstDay - 1; // Monday-first
  const daysInMonth = new Date(cy, cm + 1, 0).getDate();
  const prevMonthDays = new Date(cy, cm, 0).getDate();

  const cells = [];
  for (let i = 0; i < startOffset; i++) cells.push({ day: prevMonthDays - startOffset + 1 + i, current: false });
  for (let d = 1; d <= daysInMonth; d++) cells.push({ day: d, current: true, key: calKey(cy, cm, d) });
  while (cells.length % 7 !== 0 || cells.length < 42) cells.push({ day: cells.length - (startOffset + daysInMonth) + 1, current: false });

  const isToday = (d) => d === today.getDate() && cm === today.getMonth() && cy === today.getFullYear();
  const prev = () => { if (cm === 0) { setCm(11); setCy(cy - 1); } else setCm(cm - 1); };
  const next = () => { if (cm === 11) { setCm(0); setCy(cy + 1); } else setCm(cm + 1); };
  const goToday = () => { setCm(today.getMonth()); setCy(today.getFullYear()); };

  // upcoming list: events from today onward, sorted
  const todayKey = calKey(today.getFullYear(), today.getMonth(), today.getDate());
  const upcoming = [...CAL_EVENTS].filter(e => e.d >= todayKey).sort((a, b) => a.d.localeCompare(b.d) || a.time.localeCompare(b.time)).slice(0, 6);
  const fmtDay = (key) => { const [y, m, d] = key.split('-').map(Number); return { d, wd: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][new Date(y, m - 1, d).getDay()], mo: monthNames[m - 1].slice(0, 3) }; };

  return (
    <DashShell active="/app/dashboard/calendar">
      <div className="flex items-start justify-between gap-4 flex-wrap mb-6">
        <div>
          <h1 className="text-3xl lg:text-4xl font-bold text-ink" style={{ fontFamily: _pp }}>My Calendar</h1>
          <p className="text-sm text-neutral-500 mt-1">Your bookings, programme sessions and deadlines in one place.</p>
        </div>
        <div className="flex items-center gap-2">
          <button onClick={goToday} className="h-10 px-4 rounded-full border border-neutral-300 text-sm font-semibold hover:bg-neutral-50">Today</button>
          <div className="flex items-center gap-1">
            <button onClick={prev} aria-label="Previous month" className="w-10 h-10 rounded-full border border-neutral-300 flex items-center justify-center hover:bg-neutral-50"><Icon name="chevronLeft" size={18} /></button>
            <button onClick={next} aria-label="Next month" className="w-10 h-10 rounded-full border border-neutral-300 flex items-center justify-center hover:bg-neutral-50"><Icon name="chevronRight" size={18} /></button>
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1 xl:grid-cols-[1fr_320px] gap-6">
        {/* Month grid */}
        <div className="bg-white border border-neutral-200 rounded-2xl p-4 lg:p-5">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-xl font-bold text-ink" style={{ fontFamily: _pp }}>{monthNames[cm]} <span className="text-primary">{cy}</span></h2>
            <div className="hidden sm:flex items-center gap-3 text-[12px] text-neutral-500">
              {Object.keys(CAL_TYPE).map(k => (
                <span key={k} className="inline-flex items-center gap-1.5"><span className={`w-2 h-2 rounded-full ${CAL_TYPE[k].dot}`} />{CAL_TYPE[k].label}</span>
              ))}
            </div>
          </div>
          <div className="grid grid-cols-7 gap-1 mb-1">
            {dayNames.map(d => <div key={d} className="text-[12px] font-semibold text-neutral-400 text-center py-1">{d}</div>)}
          </div>
          <div className="grid grid-cols-7 gap-1">
            {cells.map((c, i) => {
              const evs = c.current && eventsByDay[c.key] ? eventsByDay[c.key] : [];
              const weekend = i % 7 === 5 || i % 7 === 6;
              return (
                <div key={i} className={`min-h-[92px] lg:min-h-[110px] rounded-xl border p-1.5 flex flex-col ${c.current ? 'border-neutral-200 bg-white' : 'border-transparent bg-neutral-50/60'}`}>
                  <div className="flex items-center justify-between mb-1">
                    <span className={`w-6 h-6 flex items-center justify-center text-[12px] rounded-full ${!c.current ? 'text-neutral-300' : isToday(c.day) ? 'bg-primary text-ink font-bold' : weekend ? 'text-neutral-400' : 'text-neutral-700 font-medium'}`}>{c.day}</span>
                  </div>
                  <div className="flex-1 space-y-1 overflow-hidden">
                    {evs.slice(0, 2).map((e, j) => (
                      <Link key={j} to={e.slug} title={`${e.t} · ${e.time}`} className={`block truncate px-1.5 py-1 rounded-md text-[11px] font-medium leading-tight ${CAL_TYPE[e.type].chip} hover:opacity-90`}>
                        <span className="hidden lg:inline">{e.time} · </span>{e.t}
                      </Link>
                    ))}
                    {evs.length > 2 && <span className="block px-1.5 text-[11px] font-semibold text-neutral-500">+{evs.length - 2} more</span>}
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* Upcoming list */}
        <aside className="bg-white border border-neutral-200 rounded-2xl p-5 h-fit">
          <h2 className="text-lg font-bold text-ink mb-4" style={{ fontFamily: _pp }}>Upcoming</h2>
          {upcoming.length === 0 ? (
            <p className="text-sm text-neutral-500">Nothing scheduled. Browse experiences or programmes to fill your calendar.</p>
          ) : (
            <div className="space-y-3">
              {upcoming.map((e, i) => {
                const f = fmtDay(e.d);
                return (
                  <Link key={i} to={e.slug} className="flex gap-3 group">
                    <div className="w-12 flex-shrink-0 text-center">
                      <div className="text-[11px] font-semibold text-neutral-400 uppercase">{f.wd}</div>
                      <div className="text-xl font-bold text-ink leading-none" style={{ fontFamily: _pp }}>{f.d}</div>
                      <div className="text-[11px] text-neutral-400">{f.mo}</div>
                    </div>
                    <div className="flex-1 min-w-0 border-l-2 pl-3" style={{ borderColor: 'transparent' }}>
                      <div className={`inline-flex items-center gap-1 px-2 h-5 rounded-full text-[10px] font-bold uppercase tracking-wide mb-1 ${CAL_TYPE[e.type].chip}`}><span className={`w-1.5 h-1.5 rounded-full ${CAL_TYPE[e.type].dot}`} />{CAL_TYPE[e.type].label}</div>
                      <p className="text-sm font-semibold text-ink leading-snug group-hover:text-primary-700 truncate">{e.t}</p>
                      <p className="text-xs text-neutral-500 mt-0.5 flex items-center gap-2 flex-wrap">
                        <span className="inline-flex items-center gap-1"><Icon name="clock" size={12} className="text-neutral-400" />{e.time}</span>
                        {e.loc && <span className="inline-flex items-center gap-1"><Icon name="pin" size={12} className="text-neutral-400" />{e.loc}</span>}
                      </p>
                    </div>
                  </Link>
                );
              })}
            </div>
          )}
          <Link to="/web/experiences" className="mt-5 block"><Button variant="secondary" className="w-full">Browse experiences</Button></Link>
        </aside>
      </div>
    </DashShell>
  );
}

Object.assign(window, { UserCalendarPage });
