/* eslint-disable */
;(function(){
// יפן 2026 — תזכורות (DL-056). The full reminders list: create, edit, delete.
//
// Why this screen has to exist rather than editing from the Today card: Today shows the
// 3 SOONEST FUTURE reminders (today.jsx). A 4th one, and every reminder whose date has
// passed, is invisible there — so without a list most of them could never be edited at
// all. Today stays a one-tap summary that opens the booking; editing lives here.
// `Store` is the write API — there is no top-level JP2026Store.upsert. Destructuring one
// yielded undefined and every save/delete threw "storeUpsert is not a function" on the first
// real tap. Same shape as hotelslog.jsx:13.
const { useStore, Store } = window.JP2026Store;
const { EditSheetOverlay } = window.JP2026EditorKit;
const { Icon } = window.JP2026Icons;
const reminderLabel = window.JP2026ReminderLabel || ((row) => row.label || 'תזכורת');

// Reminders are date-only strings ("2026-09-10"). Comparing them as strings is correct and
// timezone-proof — ISO dates sort lexicographically — so no Date object is built here.
const todayIso = () => {
  // Tokyo, to match the rest of the app: on the trip "today" is the local day, and a
  // reminder should stop reading as upcoming when the day turns there, not in Israel.
  const parts = new Intl.DateTimeFormat('en-CA', {
    timeZone: 'Asia/Tokyo', year: 'numeric', month: '2-digit', day: '2-digit',
  }).formatToParts(new Date());
  const get = (t) => (parts.find((p) => p.type === t) || {}).value || '';
  return `${get('year')}-${get('month')}-${get('day')}`;
};

const fmt = (iso) => {
  const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(iso || '');
  return m ? `${+m[3]}.${+m[2]}` : (iso || '');
};

function ReminderRow({ row, past, onEdit }) {
  const label = reminderLabel(row);
  return (
    <div style={{ display:'grid', gridTemplateColumns:'38px minmax(0,1fr) auto', alignItems:'center', gap:9,
      padding:'10px', borderRadius:'var(--r-md)', background:'var(--surface-card)', border:'var(--border-card)',
      boxShadow:'var(--shadow-sm)', opacity:past ? 0.55 : 1 }}>
      <span aria-hidden="true" style={{ width:38, height:38, borderRadius:12, display:'grid', placeItems:'center',
        background:past ? 'var(--vegan-none-tint)' : 'var(--sun-tint)' }}>
        <Icon name="cal" size={19} style={{ color:past ? 'var(--ink-500)' : 'var(--sun-deep)' }} />
      </span>
      <span style={{ minWidth:0 }}>
        <strong className="ltr" style={{ display:'block', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap',
          fontFamily:'var(--font-ui)', fontSize:13, color:'var(--ink-900)', fontWeight:400 }}>{label}</strong>
        <small style={{ display:'block', fontFamily:'var(--font-ui)', fontSize:11, color:'var(--ink-500)', marginTop:2 }}>
          {past ? 'היה ב־' : 'תזכורת ב־'}<span className="date-ltr">{fmt(row.date)}</span>
        </small>
      </span>
      <button type="button" onClick={()=>onEdit(row)} aria-label={`עריכת התזכורת ${label}`}
        style={{ appearance:'none', width:32, height:32, borderRadius:'50%', border:'1.5px solid var(--hairline)',
          background:'var(--surface-card)', color:'var(--ink-700)', display:'grid', placeItems:'center', cursor:'pointer' }}>
        <Icon name="pencil" size={15} />
      </button>
    </div>
  );
}

function RemindersScreen() {
  const rows = useStore('reminders');
  const bookings = useStore('bookings');
  const [sheet, setSheet] = React.useState(null);   // {init, parentDate, parentName} | null

  const live = (rows || []).filter((row) => !row.deleted_at && row.date);
  const iso = todayIso();
  const sortByDate = (a, b) => (a.date === b.date ? 0 : a.date < b.date ? -1 : 1);
  const upcoming = live.filter((row) => row.date >= iso).sort(sortByDate);
  // Past reads newest-first: the thing that just lapsed is the one worth seeing.
  const past = live.filter((row) => row.date < iso).sort((a, b) => sortByDate(b, a));

  const parentOf = (row) => (bookings || []).find((b) => b.id === row.parent_id) || null;

  const openEdit = (row) => {
    const parent = parentOf(row);
    setSheet({
      init: row,
      parentDate: parent ? (parent.date_iso || '') : '',
      parentName: parent ? (parent.name || parent.nameLatin || '') : '',
    });
  };
  // A create sheet is an `init` with NO id — useSheet hides the delete button on exactly
  // that condition, and Store.upsert mints the uuid (the discover.jsx:456 pattern).
  const openCreate = () => setSheet({ init:{ label:'', date:'' }, parentDate:'', parentName:'' });

  const save = (form) => {
    const next = { ...form, label:(form.label || '').trim(), date:(form.date || '').trim() };
    if (!next.label || !/^\d{4}-\d{2}-\d{2}$/.test(next.date)) return;  // the DB CHECKs both
    Store.upsert('reminders', next);
  };
  // Soft delete, NOT Store.remove. reminders-sync.js reads deleted_at to carry the deletion
  // back to export/reminders.csv; a hard delete leaves nothing to say the row was removed on
  // purpose, and the next desk sync would re-add it.
  const remove = (id) => {
    const row = live.find((r) => r.id === id);
    if (row) Store.upsert('reminders', { ...row, deleted_at:new Date().toISOString() });
  };

  const Group = ({ title, items, past:isPast }) => items.length > 0 && (
    <>
      <div style={{ fontFamily:'var(--font-ui)', fontSize:11, color:'var(--ink-500)', margin:'14px 2px 4px' }}>{title}</div>
      <div style={{ display:'grid', gap:8 }}>
        {items.map((row) => <ReminderRow key={row.id} row={row} past={isPast} onEdit={openEdit} />)}
      </div>
    </>
  );

  return (
    <div style={{ padding:'14px 20px 24px' }}>
      <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', gap:8, margin:'0 2px 4px' }}>
        <h1 style={{ fontFamily:'var(--font-display)', fontSize:40, lineHeight:1, color:'var(--ink-900)', margin:0 }}>תזכורות</h1>
        <button type="button" onClick={openCreate}
          style={{ appearance:'none', cursor:'pointer', display:'inline-flex', alignItems:'center', gap:6,
            padding:'6px 14px', borderRadius:'var(--r-pill)', border:'1.5px solid var(--sun-deep)',
            background:'var(--surface-card)', color:'var(--ink-700)', fontFamily:'var(--font-ui)', fontSize:14 }}>
          {/* Sprite icon, never the ＋ character — DL-040 replaced the text-glyph icons
              precisely because they are a separate, unstyleable icon system. */}
          <Icon name="plus" size={16} style={{ color:'var(--sun-deep)' }} /> חדשה
        </button>
      </div>

      {live.length === 0 && (
        <div style={{ marginTop:18, padding:'12px 14px', borderRadius:'var(--r-md)', background:'var(--matcha-tint)',
          color:'var(--matcha-deep)', fontFamily:'var(--font-ui)', fontSize:13 }}>
          אין תזכורות. אפשר להוסיף אחת עם הכפתור למעלה.
        </div>
      )}

      <Group title="קרוב" items={upcoming} past={false} />
      <Group title="עבר" items={past} past={true} />

      {sheet && (
        <EditSheetOverlay type="reminder" init={sheet.init}
          parentDate={sheet.parentDate} parentName={sheet.parentName}
          onClose={()=>setSheet(null)} onSave={save} onDelete={remove} />
      )}
    </div>
  );
}

window.JP2026Reminders = RemindersScreen;

})();
