// screen-calendar.jsx — agenda + add/edit event (bilingual, Gregorian)
const EVENT_TYPES = [
  { id: 'jy', colorKey: 'accent' },
  { id: 'children', colorKey: 'star' },
];

function CalendarScreen({ events, addEvent, isCoordinator, setCoordinator, route, clearFocus }) {
  const c = useTheme();
  const U = window.ASFUtil;
  const [filter, setFilter] = React.useState('all');
  const [adding, setAdding] = React.useState(false);
  const [detail, setDetail] = React.useState(null);

  React.useEffect(() => {
    if (route.focus) { const e = events.find(x => x.id === route.focus); if (e) setDetail(e); clearFocus(); }
  }, [route.focus]);

  const tColor = (k) => c[(EVENT_TYPES.find(t => t.id === k) || EVENT_TYPES[0]).colorKey];
  const list = [...events].map(e => ({ ...e, _d: new Date(e.start) }))
    .filter(e => filter === 'all' || e.type === filter)
    .sort((a, b) => a._d - b._d);

  const groups = [];
  list.forEach(e => {
    const key = e._d.toDateString();
    let g = groups.find(x => x.key === key);
    if (!g) { g = { key, d: e._d, items: [] }; groups.push(g); }
    g.items.push(e);
  });

  return (
    <div style={{ padding: '58px 18px 120px' }}>
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 6 }}>
        <h1 style={{ margin: '0 2px', fontFamily: c.headingStack, fontWeight: 600, fontSize: 32, color: c.text }}>{c.t('calendar')}</h1>
      </div>
      <p style={{ margin: '0 2px 16px', color: c.textMuted, fontSize: 14.5 }}>{c.t('calendar_sub')}</p>

      <div style={{ display: 'flex', gap: 8, overflowX: 'auto', margin: '0 -18px 18px', padding: '0 18px' }}>
        <Chip active={filter === 'all'} onClick={() => setFilter('all')}>{c.t('all')}</Chip>
        {EVENT_TYPES.map(t => <Chip key={t.id} active={filter === t.id} onClick={() => setFilter(t.id)}>{c.t('et_' + t.id)}</Chip>)}
      </div>

      {groups.length === 0 && <Empty>{c.t('no_match')}</Empty>}
      {groups.map(g => (
        <div key={g.key} style={{ marginBottom: 22 }}>
          {(() => { const dl = U.dayLabel(g.d, c.lang); const rel = dl === c.t('today') || dl === c.t('tomorrow'); return (
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, margin: '0 2px 10px', whiteSpace: 'nowrap' }}>
            <span style={{ fontFamily: c.headingStack, fontSize: 17, fontWeight: 600, color: c.text }}>{dl}</span>
            {rel && <span style={{ fontSize: 12.5, color: c.textMuted }}>{U.mon(c.lang, g.d.getMonth())} {g.d.getDate()}</span>}
          </div>
          ); })()}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {g.items.map(e => (
              <button key={e.id} onClick={() => setDetail(e)} style={{ ...asfCardBtn(c), padding: 0, overflow: 'hidden' }}>
                <div style={{ display: 'flex' }}>
                  <div style={{ width: 4, background: tColor(e.type), flexShrink: 0 }} />
                  <div style={{ flex: 1, padding: '14px 16px', textAlign: 'left' }}>
                    <div style={{ fontSize: 16, fontWeight: 700, color: c.text }}>{c.L(e.title)}</div>
                    <div style={{ fontSize: 13, color: c.textMuted, marginTop: 4, display: 'flex', flexWrap: 'wrap', gap: '4px 12px' }}>
                      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}><Icon name="clock" size={13} />{U.fmtTime(e.start)}</span>
                      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}><Icon name="pin" size={13} />{c.L(e.place)}</span>
                    </div>
                  </div>
                </div>
              </button>
            ))}
          </div>
        </div>
      ))}

      <EventDetail event={detail} onClose={() => setDetail(null)} tColor={tColor} />
      <AddEvent open={adding} onClose={() => setAdding(false)} onSave={(e) => { addEvent(e); setAdding(false); }} />
    </div>
  );
}

function EventDetail({ event, onClose, tColor }) {
  const c = useTheme();
  const U = window.ASFUtil;
  if (!event) return null;
  const d = new Date(event.start);
  const rows = [
    ['clock', `${U.dayLabel(d, c.lang)} · ${U.fmtTime(event.start)}${event.end ? ' – ' + U.fmtTime(event.end) : ''}`],
    ['pin', c.L(event.place)],
    event.host ? ['user', `${c.t('hosted_by')} ${event.host}`] : null,
  ].filter(Boolean);
  return (
    <Sheet open={!!event} onClose={onClose}>
      <div style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '5px 11px', borderRadius: 99, background: c.accentSoft, color: tColor(event.type), fontSize: 12.5, fontWeight: 700 }}>
        <span style={{ width: 8, height: 8, borderRadius: 99, background: tColor(event.type) }} />{c.t('et_' + event.type)}
      </div>
      <h2 style={{ fontFamily: c.headingStack, fontSize: 26, fontWeight: 600, color: c.text, margin: '12px 0 18px', lineHeight: 1.15 }}>{c.L(event.title)}</h2>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        {rows.map(([ic, txt], i) => (
          <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, color: c.text }}>
            <div style={{ color: c.textMuted }}><Icon name={ic} size={19} /></div>
            <span style={{ fontSize: 15.5 }}>{txt}</span>
          </div>
        ))}
        {event.note && <p style={{ margin: '4px 0 0', fontSize: 15, lineHeight: 1.55, color: c.textMuted }}>{c.L(event.note)}</p>}
      </div>
      <button onClick={onClose} style={{ width: '100%', marginTop: 24, border: 'none', cursor: 'pointer', background: c.text, color: c.bg, fontFamily: 'inherit', fontWeight: 700, fontSize: 15.5, padding: '15px', borderRadius: 14 }}>{c.t('add_to_cal')}</button>
    </Sheet>
  );
}

function AddEvent({ open, onClose, onSave }) {
  const c = useTheme();
  const [f, setF] = React.useState({ title: '', type: 'jy', date: '', time: '16:00', place: '', host: '', note: '' });
  const set = (k, v) => setF(p => ({ ...p, [k]: v }));
  const valid = f.title.trim() && f.date && f.place.trim();
  const submit = () => {
    const start = new Date(`${f.date}T${f.time || '12:00'}`);
    onSave({ id: 'e' + Date.now(), title: f.title.trim(), type: f.type, start: start.toISOString(), place: f.place.trim(), host: f.host.trim(), note: f.note.trim() });
    setF({ title: '', type: 'jy', date: '', time: '16:00', place: '', host: '', note: '' });
  };
  const inp = { width: '100%', boxSizing: 'border-box', border: `1px solid ${c.border}`, background: c.surfaceAlt, color: c.text, borderRadius: 12, padding: '13px 14px', fontFamily: 'inherit', fontSize: 15.5, outline: 'none' };
  const lab = { fontSize: 12.5, fontWeight: 700, letterSpacing: '0.04em', textTransform: 'uppercase', color: c.textMuted, margin: '0 2px 7px' };

  return (
    <Sheet open={open} onClose={onClose} title={c.t('new_event')}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        <div><div style={lab}>{c.t('f_title')}</div><input value={f.title} onChange={e => set('title', e.target.value)} style={inp} /></div>
        <div>
          <div style={lab}>{c.t('f_type')}</div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
            {EVENT_TYPES.map(t => <Chip key={t.id} active={f.type === t.id} onClick={() => set('type', t.id)}>{c.t('et_' + t.id)}</Chip>)}
          </div>
        </div>
        <div style={{ display: 'flex', gap: 12 }}>
          <div style={{ flex: 1 }}><div style={lab}>{c.t('f_date')}</div><input type="date" value={f.date} onChange={e => set('date', e.target.value)} style={inp} /></div>
          <div style={{ width: 130 }}><div style={lab}>{c.t('f_time')}</div><input type="time" value={f.time} onChange={e => set('time', e.target.value)} style={inp} /></div>
        </div>
        <div><div style={lab}>{c.t('f_place')}</div><input value={f.place} onChange={e => set('place', e.target.value)} style={inp} /></div>
        <div><div style={lab}>{c.t('f_host')}</div><input value={f.host} onChange={e => set('host', e.target.value)} style={inp} /></div>
        <div><div style={lab}>{c.t('f_note')}</div><textarea value={f.note} onChange={e => set('note', e.target.value)} style={{ ...inp, minHeight: 70, resize: 'none' }} /></div>
        <button onClick={submit} disabled={!valid} style={{ border: 'none', cursor: valid ? 'pointer' : 'default', background: valid ? c.accent : c.border, color: valid ? c.accentInk : c.textMuted, fontFamily: 'inherit', fontWeight: 700, fontSize: 16, padding: '16px', borderRadius: 14 }}>{c.t('add_event')}</button>
      </div>
    </Sheet>
  );
}

Object.assign(window, { CalendarScreen });
