/* Track & Train — Types management tab */

function TypesView({ data, lang, onSetLang, onAddType, onUpdateType, onDeleteType, onImport, onReset }) {
  const [editing, setEditing] = useState(null);   // type being edited, or { isNew:true }
  const { ask, ui: confirmUI } = useConfirm();
  const toast = useToast();
  const fileRef = useRef(null);

  const exportData = () => {
    const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url; a.download = `track-train-${todayKey()}.json`;
    document.body.appendChild(a); a.click(); a.remove();
    setTimeout(() => URL.revokeObjectURL(url), 1000);
    toast(t('export_done'));
  };
  const onFile = async (e) => {
    const file = e.target.files && e.target.files[0];
    e.target.value = '';
    if (!file) return;
    let parsed;
    try { parsed = JSON.parse(await file.text()); }
    catch (err) { toast(t('import_error')); return; }
    if (!parsed || !Array.isArray(parsed.types) || !Array.isArray(parsed.sessions)) { toast(t('import_error')); return; }
    const ok = await ask({ title: t('import_confirm_title'), message: t('import_confirm_msg'), confirmLabel: t('import'), danger: true });
    if (ok) { onImport({ types: parsed.types, sessions: parsed.sessions }); toast(t('import_done')); }
  };

  const countByType = useMemo(() => {
    const m = {};
    for (const s of data.sessions) m[s.typeId] = (m[s.typeId] || 0) + 1;
    return m;
  }, [data.sessions]);

  const startNew = () => {
    const firstFree = TYPE_COLORS.find(c => !data.types.map(t => t.color).includes(c)) || TYPE_COLORS[0];
    setEditing({ isNew: true, id: uid('typ'), name: '', color: firstFree });
  };
  const save = () => {
    const name = editing.name.trim();
    if (!name) return;
    if (editing.isNew) onAddType(name, editing.color, editing.id);
    else onUpdateType({ id: editing.id, name, color: editing.color });
    setEditing(null);
  };
  const remove = async (ty) => {
    const n = countByType[ty.id] || 0;
    const ok = await ask({
      title: t('del_type_title', { name: ty.name }),
      message: n > 0 ? t(n > 1 ? 'del_type_msg_with_p' : 'del_type_msg_with', { n }) : t('del_type_msg_none'),
      confirmLabel: t('delete'), danger: true,
    });
    if (ok) { onDeleteType(ty.id); setEditing(null); toast(t('type_deleted')); }
  };

  return (
    <div className="fade-in">
      <div className="section-label" style={{ paddingTop: 8 }}>{t('language')}</div>
      <div className="segmented block" style={{ display: 'flex', width: '100%' }}>
        {LANGS.map(l => (
          <button key={l.id} className={lang === l.id ? 'active' : ''} onClick={() => onSetLang(l.id)} style={{ flex: 1, justifyContent: 'center' }}>
            {l.name}
          </button>
        ))}
      </div>

      <div className="section-label" style={{ paddingTop: 24 }}>
        <span>{t('types_title')}</span>
        <span className="muted" style={{ textTransform: 'none', letterSpacing: 0, fontWeight: 500 }}>{data.types.length}</span>
      </div>

      {data.types.map(ty => (
        <button key={ty.id} className="row" style={{ marginBottom: 8 }} onClick={() => setEditing({ ...ty })}>
          <span className="type-swatch" style={{ background: ty.color }}></span>
          <span className="row-main">
            <span className="row-title">{ty.name}</span>
            <span className="row-sub">{nSessions(countByType[ty.id] || 0)}</span>
          </span>
          <span style={{ color: 'var(--ink-4)' }}><Icon.chev/></span>
        </button>
      ))}

      <button className="type-chip add" style={{ marginTop: 6, padding: '12px 16px', width: '100%', justifyContent: 'center', borderRadius: 'var(--radius)' }} onClick={startNew}>
        <Icon.plusSm/> {t('add_type')}
      </button>

      <div className="section-label" style={{ paddingTop: 26 }}>{t('data')}</div>
      <div className="card">
        <div className="flex items-center between">
          <div>
            <div style={{ fontWeight: 600, fontSize: 14.5 }}>{t('export')}</div>
            <div className="muted small" style={{ marginTop: 2 }}>{t('export_desc')}</div>
          </div>
          <button className="btn secondary sm" onClick={exportData}><Icon.download/> {t('export')}</button>
        </div>
        <div style={{ height: 1, background: 'var(--line)', margin: '13px 0' }}></div>
        <div className="flex items-center between">
          <div>
            <div style={{ fontWeight: 600, fontSize: 14.5 }}>{t('import')}</div>
            <div className="muted small" style={{ marginTop: 2 }}>{t('import_desc')}</div>
          </div>
          <button className="btn secondary sm" onClick={() => fileRef.current && fileRef.current.click()}><Icon.upload/> {t('import')}</button>
        </div>
        <input ref={fileRef} type="file" accept="application/json,.json" className="hidden" onChange={onFile} />
      </div>
      <div className="card" style={{ marginTop: 10 }}>
        <div className="flex items-center between">
          <div>
            <div style={{ fontWeight: 600, fontSize: 14.5 }}>{t('reset')}</div>
            <div className="muted small" style={{ marginTop: 2 }}>{t('reset_desc')}</div>
          </div>
          <button className="btn secondary sm" onClick={async () => {
            const ok = await ask({ title: t('reset_confirm_title'), message: t('reset_confirm_msg'), confirmLabel: t('reset'), danger: true });
            if (ok) { onReset(); toast(t('reset_done')); }
          }}>{t('reset')}</button>
        </div>
      </div>
      <p className="muted small text-center" style={{ marginTop: 16 }}>
        {t('data_local')}
      </p>

      {/* edit / new type sheet */}
      <Sheet
        open={!!editing}
        onClose={() => setEditing(null)}
        title={editing ? (editing.isNew ? t('newtype_title') : t('edittype_title')) : ''}
        action={editing && !editing.isNew
          ? <button className="icon-btn" style={{ color: 'var(--ink-3)' }} onClick={() => remove(editing)} aria-label={t('delete')}><Icon.trash/></button>
          : null}
      >
        {editing && (
          <div className="flex" style={{ flexDirection: 'column', gap: 16 }}>
            <div className="field">
              <label>{t('name')}</label>
              <input className="input" autoFocus value={editing.name}
                placeholder={t('nt_name_ph')}
                onChange={e => setEditing(s => ({ ...s, name: e.target.value }))}
                onKeyDown={e => { if (e.key === 'Enter' && editing.name.trim()) save(); }} />
            </div>
            <div className="field">
              <label>{t('nt_color')}</label>
              <ColorPicker value={editing.color} onChange={(c) => setEditing(s => ({ ...s, color: c }))} />
            </div>
            <button className="btn accent block lg" style={{ marginTop: 6 }} disabled={!editing.name.trim()} onClick={save}>
              {editing.isNew ? t('create_type') : t('save')}
            </button>
          </div>
        )}
      </Sheet>

      {confirmUI}
    </div>
  );
}

Object.assign(window, { TypesView });
