// Calendar / Agenda screen — week view + day timeline

const CalendarScreen = ({ state, setState, navigate, showToast }) => {
  const [view, setView] = React.useState('dia');
  const [selectedDay, setSelectedDay] = React.useState(3); // index of week
  const [showNew, setShowNew] = React.useState(false);
  const events = (state && state.events) || eventsToday;

  const addEvent = (ev) => {
    setState && setState(s => ({ ...s, events: [...(s.events || eventsToday), { ...ev, id: 'ev' + Date.now() }] }));
    setShowNew(false);
    showToast && showToast('Evento criado');
  };

  const weekDays = [
    { d: 'Seg', n: 16, today: false },
    { d: 'Ter', n: 17, today: false },
    { d: 'Qua', n: 18, today: false },
    { d: 'Qui', n: 19, today: true },
    { d: 'Sex', n: 20, today: false },
    { d: 'Sáb', n: 21, today: false },
    { d: 'Dom', n: 22, today: false },
  ];

  return (
    <div style={{ paddingBottom: 110 }}>
      <Header title="Agenda" subtitle="JUNHO DE 2026" onBack={() => navigate('dashboard')} right={
        <button onClick={() => setShowNew(true)} style={{
          background: CDV.brandGrad, border: 'none', width: 38, height: 38, borderRadius: 99,
          display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff',
        }}><Icon name="plus" size={18} /></button>
      } />

      {/* View switcher */}
      <div style={{ padding: '0 22px 14px' }}>
        <div style={{ display: 'flex', gap: 4, background: CDV.surface, border: `1px solid ${CDV.stroke}`, padding: 4, borderRadius: 12 }}>
          {[{ id: 'dia', label: 'Dia' }, { id: 'semana', label: 'Semana' }, { id: 'mes', label: 'Mês' }].map(v => (
            <button key={v.id} onClick={() => setView(v.id)} style={{
              flex: 1, height: 32, borderRadius: 8,
              background: view === v.id ? CDV.surfaceHi2 : 'transparent',
              color: view === v.id ? CDV.text : CDV.textDim,
              border: 'none', fontSize: 13, fontWeight: 600, fontFamily: 'inherit',
            }}>{v.label}</button>
          ))}
        </div>
      </div>

      {/* Week strip */}
      <div style={{ padding: '0 22px 18px' }}>
        <div style={{ display: 'flex', gap: 6 }}>
          {weekDays.map((d, i) => {
            const active = selectedDay === i;
            return (
              <button key={i} onClick={() => setSelectedDay(i)} style={{
                flex: 1, height: 72, borderRadius: 16,
                background: active ? CDV.brandGrad : d.today ? CDV.brandSoft : CDV.surface,
                border: `1px solid ${active ? 'transparent' : d.today ? CDV.brand + '40' : CDV.stroke}`,
                color: active ? '#fff' : CDV.text,
                display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
                gap: 4, fontFamily: 'inherit',
                boxShadow: active ? '0 8px 20px -6px rgba(177,151,252,0.4)' : 'none',
              }}>
                <div style={{ fontSize: 11, fontWeight: 600, opacity: 0.75 }}>{d.d}</div>
                <div style={{ fontSize: 20, fontWeight: 700, letterSpacing: -0.3 }}>{d.n}</div>
                {d.today && !active && <div style={{ width: 4, height: 4, borderRadius: 99, background: CDV.brand }} />}
                {active && <div style={{ width: 4, height: 4, borderRadius: 99, background: '#fff' }} />}
              </button>
            );
          })}
        </div>
      </div>

      {view === 'dia' && <DayView events={events} />}
      {view === 'semana' && <WeekView events={events} />}
      {view === 'mes' && <MonthView />}

      <Sheet open={showNew} onClose={() => setShowNew(false)} title="Novo evento">
        <NewEventForm onSubmit={addEvent} />
      </Sheet>
    </div>
  );
};

const NewEventForm = ({ onSubmit }) => {
  const [title, setTitle] = React.useState('');
  const [start, setStart] = React.useState('14');
  const [end, setEnd] = React.useState('15');
  const [location, setLocation] = React.useState('');
  const colors = [CDV.brand, CDV.mint, CDV.coral, CDV.amber, CDV.sky];
  const [color, setColor] = React.useState(colors[0]);

  const canSave = title.trim() && Number(start) < Number(end);

  return (
    <div style={{ padding: '12px 20px 28px' }}>
      <input value={title} onChange={e => setTitle(e.target.value)} placeholder="Título do evento"
        style={{
          width: '100%', height: 54, borderRadius: 16, border: `1px solid ${CDV.stroke}`,
          background: CDV.surfaceHi, color: CDV.text, padding: '0 16px', fontSize: 15,
          outline: 'none', fontFamily: 'inherit', marginBottom: 12,
        }} />

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 12 }}>
        <div style={{ background: CDV.surfaceHi, border: `1px solid ${CDV.stroke}`, borderRadius: 14, padding: 12 }}>
          <div style={{ fontSize: 10, color: CDV.textMuted, fontWeight: 600, letterSpacing: 0.3, textTransform: 'uppercase' }}>Início (h)</div>
          <input type="number" min="0" max="23" value={start} onChange={e => setStart(e.target.value)}
            style={{ width: '100%', background: 'transparent', border: 'none', outline: 'none', color: CDV.text, fontSize: 16, fontWeight: 600, marginTop: 4, fontFamily: 'inherit' }} />
        </div>
        <div style={{ background: CDV.surfaceHi, border: `1px solid ${CDV.stroke}`, borderRadius: 14, padding: 12 }}>
          <div style={{ fontSize: 10, color: CDV.textMuted, fontWeight: 600, letterSpacing: 0.3, textTransform: 'uppercase' }}>Fim (h)</div>
          <input type="number" min="0" max="23" value={end} onChange={e => setEnd(e.target.value)}
            style={{ width: '100%', background: 'transparent', border: 'none', outline: 'none', color: CDV.text, fontSize: 16, fontWeight: 600, marginTop: 4, fontFamily: 'inherit' }} />
        </div>
      </div>

      <input value={location} onChange={e => setLocation(e.target.value)} placeholder="Local (opcional)"
        style={{
          width: '100%', height: 50, borderRadius: 14, border: `1px solid ${CDV.stroke}`,
          background: CDV.surfaceHi, color: CDV.text, padding: '0 16px', fontSize: 14,
          outline: 'none', fontFamily: 'inherit', marginBottom: 12,
        }} />

      <div style={{ fontSize: 12, color: CDV.textDim, fontWeight: 600, letterSpacing: 0.4, textTransform: 'uppercase', marginBottom: 8 }}>Cor</div>
      <div style={{ display: 'flex', gap: 8, marginBottom: 18 }}>
        {colors.map(c => (
          <button key={c} onClick={() => setColor(c)} style={{
            width: 34, height: 34, borderRadius: 99, background: c,
            border: color === c ? `2.5px solid ${CDV.text}` : '2.5px solid transparent',
            cursor: 'pointer',
          }} />
        ))}
      </div>

      <button onClick={() => canSave && onSubmit({ title, start: Number(start), end: Number(end), location: location || '—', color })} style={{
        width: '100%', height: 54, borderRadius: 16,
        background: CDV.brandGrad, border: 'none', color: '#fff', fontWeight: 600, fontSize: 15,
        opacity: canSave ? 1 : 0.4,
      }}>Criar evento</button>
    </div>
  );
};

const DayView = ({ events }) => {
  const hours = Array.from({ length: 14 }, (_, i) => i + 7); // 7 to 20
  const HOUR_HEIGHT = 56;
  const nowHour = 10.4;

  return (
    <div style={{ padding: '0 22px 24px' }}>
      <div style={{
        background: CDV.surface, border: `1px solid ${CDV.stroke}`, borderRadius: 22,
        padding: '14px 8px', position: 'relative', overflow: 'hidden',
      }}>
        <div style={{ position: 'relative' }}>
          {hours.map(h => (
            <div key={h} style={{
              display: 'flex', height: HOUR_HEIGHT, alignItems: 'flex-start',
              borderTop: h === hours[0] ? 'none' : `1px solid ${CDV.divider}`,
            }}>
              <div style={{
                width: 52, paddingLeft: 8, paddingTop: 6, fontSize: 11, color: CDV.textMuted, fontWeight: 600,
              }}>{String(h).padStart(2, '0')}:00</div>
              <div style={{ flex: 1 }} />
            </div>
          ))}

          {/* Events */}
          {events.map(ev => {
            const top = (ev.start - hours[0]) * HOUR_HEIGHT + 14;
            const height = (ev.end - ev.start) * HOUR_HEIGHT - 4;
            return (
              <div key={ev.id} style={{
                position: 'absolute', top, left: 60, right: 8,
                height, padding: '8px 12px', borderRadius: 12,
                background: `linear-gradient(135deg, ${ev.color}28, ${ev.color}12)`,
                borderLeft: `3px solid ${ev.color}`,
              }}>
                <div style={{ fontSize: 12, fontWeight: 600, color: CDV.text, lineHeight: 1.2 }}>{ev.title}</div>
                <div style={{ fontSize: 10, color: CDV.textDim, marginTop: 3 }}>
                  {fmtHour(ev.start)} – {fmtHour(ev.end)} · {ev.location}
                </div>
              </div>
            );
          })}

          {/* Now indicator */}
          <div style={{ position: 'absolute', top: (nowHour - hours[0]) * HOUR_HEIGHT + 14, left: 50, right: 0, height: 0, pointerEvents: 'none' }}>
            <div style={{ position: 'relative', height: 0 }}>
              <div style={{ position: 'absolute', left: 0, top: -4, width: 8, height: 8, borderRadius: 99, background: CDV.coral }} />
              <div style={{ position: 'absolute', left: 10, right: 8, top: -1, height: 2, background: CDV.coral, borderRadius: 1 }} />
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

const fmtHour = (h) => {
  const hh = Math.floor(h);
  const mm = Math.round((h - hh) * 60);
  return `${String(hh).padStart(2, '0')}:${String(mm).padStart(2, '0')}`;
};

const WeekView = ({ events }) => (
  <div style={{ padding: '0 22px 24px' }}>
    <Card padding={18}>
      <div style={{ fontSize: 13, color: CDV.textDim, marginBottom: 12 }}>Semana de 16-22 Jun</div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 4 }}>
        {[...Array(7)].map((_, i) => (
          <div key={i} style={{ display: 'flex', flexDirection: 'column', gap: 3, alignItems: 'center' }}>
            <div style={{ fontSize: 10, color: CDV.textDim, marginBottom: 4 }}>{['S','T','Q','Q','S','S','D'][i]}</div>
            <div style={{
              width: 28, height: 28, borderRadius: 8,
              background: i === 3 ? CDV.brand : 'transparent',
              color: i === 3 ? '#fff' : CDV.text,
              fontSize: 12, fontWeight: 600,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>{16 + i}</div>
            {Array.from({ length: Math.floor(Math.random() * 4) + 1 }, (_, k) => (
              <div key={k} style={{ width: 6, height: 6, borderRadius: 99, background: [CDV.brand, CDV.mint, CDV.coral, CDV.amber][k % 4] }} />
            ))}
          </div>
        ))}
      </div>
    </Card>

    <SectionHeader title="Eventos da semana" />
    <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      {events.slice(0, 4).map(ev => (
        <div key={ev.id} style={{
          padding: 12, borderRadius: 14, background: CDV.surface, border: `1px solid ${CDV.stroke}`,
          display: 'flex', alignItems: 'center', gap: 12,
        }}>
          <div style={{ width: 3, height: 38, borderRadius: 2, background: ev.color }} />
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 13, fontWeight: 500 }}>{ev.title}</div>
            <div style={{ fontSize: 11, color: CDV.textDim, marginTop: 2 }}>{fmtHour(ev.start)} - {fmtHour(ev.end)} · {ev.location}</div>
          </div>
        </div>
      ))}
    </div>
  </div>
);

const MonthView = () => {
  const dots = { 3: 4, 7: 2, 10: 3, 14: 1, 16: 2, 19: 5, 22: 2, 25: 3, 28: 1 };
  return (
    <div style={{ padding: '0 22px 24px' }}>
      <Card padding={18}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 4, marginBottom: 8 }}>
          {['D','S','T','Q','Q','S','S'].map(d => (
            <div key={d} style={{ fontSize: 10, color: CDV.textDim, textAlign: 'center', fontWeight: 600 }}>{d}</div>
          ))}
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 4 }}>
          {[...Array(35)].map((_, i) => {
            const day = i - 2;
            if (day < 1 || day > 30) return <div key={i} style={{ height: 44 }} />;
            const today = day === 19;
            return (
              <div key={i} style={{
                height: 44, borderRadius: 8, padding: 4,
                background: today ? CDV.brandGrad : 'transparent',
                display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2,
              }}>
                <div style={{ fontSize: 12, fontWeight: 600, color: today ? '#fff' : CDV.text }}>{day}</div>
                <div style={{ display: 'flex', gap: 2 }}>
                  {Array.from({ length: dots[day] || 0 }, (_, k) => (
                    <div key={k} style={{ width: 4, height: 4, borderRadius: 99, background: today ? '#fff' : [CDV.brand, CDV.mint, CDV.coral][k % 3] }} />
                  ))}
                </div>
              </div>
            );
          })}
        </div>
      </Card>
    </div>
  );
};

Object.assign(window, { CalendarScreen });
