// RentFlow Manager Desktop — App shell: macOS window chrome + sidebar nav + state.

const { useState, useEffect, useMemo, useRef } = React;

const CATEGORIES = ['Tontechnik', 'Anhänger', 'Licht', 'Sonstiges'];

const NAV = [
  { id: 'dashboard', label: 'Übersicht',     icon: icons.home },
  { id: 'rentals',   label: 'Mietaufträge',  icon: icons.doc },
  { id: 'calendar',  label: 'Kalender',      icon: icons.cal },
  { id: 'equipment', label: 'Equipment',     icon: icons.truck },
  { id: 'finance',   label: 'Finanzen',      icon: icons.euro },
  { id: 'inbox',     label: 'Posteingang',   icon: icons.mail },
  { id: 'documents', label: 'Dokumente',     icon: icons.fileText },
];

// ── Convert email → rental dialog ──
function ConvertSheet({ open, email, equipment, onClose, onCreate }) {
  const t = useTheme();
  const p = email && email.parsed;
  const guessId = p ? matchEquipmentId(p.equipmentHint, equipment) : (equipment[0] && equipment[0].id);
  const [form, setForm] = useState({});
  useEffect(() => {
    if (open && email) {
      const eqId = guessId || (equipment[0] && equipment[0].id);
      const eq = equipment.find((e) => e.id === eqId);
      setForm({
        tenantName: email.from, email: email.fromEmail, phone: (p && p.phone) || '',
        address: (p && p.deliveryAddress) || '', equipmentId: eqId,
        purpose: (p && p.purpose) || '', start: (p && p.startISO) || todayISO(), end: (p && p.endISO) || tomorrowISO(),
        startTime: '14:00', endTime: '11:00', dailyRate: eq ? eq.price : 0, deposit: 100, quantity: 1,
        depositStatus: 'offen', paymentStatus: 'offen',
      });
    }
  }, [open, email && email.id]);
  if (!email) return null;
  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));
  const eq = equipment.find((e) => e.id === form.equipmentId);
  const days = daysBetween(form.start || todayISO(), form.end || todayISO());

  return (
    <Sheet open={open} onClose={onClose} width={560}>
      <div style={{ padding: '4px 26px 24px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
          <div><div style={{ fontSize: 21, fontWeight: 700, color: t.text, letterSpacing: -0.4, display: 'flex', alignItems: 'center', gap: 8 }}><Icon d={icons.bolt} color={t.accent} size={19} sw={2.2}/> Anfrage umwandeln</div><div style={{ fontSize: 12.5, color: t.textSec, marginTop: 4 }}>Aus der E-Mail einen Mietvorgang erstellen.</div></div>
          <Pressable onClick={onClose}><div style={{ fontSize: 14, color: t.textSec, fontWeight: 500 }}>Abbrechen</div></Pressable>
        </div>
        <Field label="Mieter"><TextInput value={form.tenantName || ''} onChange={(e) => set('tenantName', e.target.value)}/></Field>
        <Field label="Equipment">
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
            {equipment.map((e) => (
              <Pressable key={e.id} onClick={() => { set('equipmentId', e.id); set('dailyRate', e.price); }} scale={0.96}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '7px 11px 7px 7px', borderRadius: 10, background: form.equipmentId === e.id ? t.accentSoft : t.chip, border: form.equipmentId === e.id ? `1.5px solid ${t.accent}` : '1.5px solid transparent' }}><EqAvatar item={e} size={26} radius={6}/><span style={{ fontSize: 12.5, fontWeight: 600, color: form.equipmentId === e.id ? t.accent : t.text }}>{e.name}</span></div>
              </Pressable>
            ))}
          </div>
        </Field>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
          <Field label="Von"><TextInput type="date" value={form.start || ''} onChange={(e) => set('start', e.target.value)}/></Field>
          <Field label="Bis"><TextInput type="date" value={form.end || ''} onChange={(e) => set('end', e.target.value)}/></Field>
        </div>
        <Field label="Zweck"><TextInput value={form.purpose || ''} onChange={(e) => set('purpose', e.target.value)}/></Field>
        <div style={{ marginTop: 18, padding: '13px 16px', borderRadius: 12, background: t.cardAlt, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div style={{ fontSize: 12.5, color: t.textSec }}>{days} Tag{days > 1 ? 'e' : ''} × {form.dailyRate || 0} €</div>
          <div style={{ fontSize: 20, fontWeight: 700, color: t.text, ...NUMS }}>{rentalTotal(form)} €</div>
        </div>
        <Pressable onClick={() => { const status = autoRentalStatus(form.start, form.end); onCreate({ ...form, id: 'r-' + Date.now(), status, equipmentName: eq ? eq.name : '', idCard: '' }); onClose(); }} scale={0.98} style={{ marginTop: 16 }}>
          <div style={{ padding: '14px 0', textAlign: 'center', borderRadius: 12, background: t.accent, color: '#fff', fontSize: 15, fontWeight: 700, boxShadow: '0 6px 16px rgba(0,122,255,0.32)' }}>Mietvorgang erstellen</div>
        </Pressable>
      </div>
    </Sheet>
  );
}

function App() {
  const [dark, setDark] = useLocal('rf-d-dark', false);
  const theme = dark ? darkTheme : lightTheme;
  const [screen, setScreen] = useState('dashboard');
  const [nav, setNav] = useState({});
  const [equipment, setEquipment] = useLocal('rf-d-equipment', SEED_EQUIPMENT);
  const [rentals, setRentals] = useLocal('rf-d-rentals', SEED_RENTALS);
  const [events, setEvents] = useLocal('rf-d-events', SEED_EVENTS);
  const [tasks, setTasks] = useLocal('rf-d-tasks', { items: [], autoDone: {} });
  const [company, setCompany] = useLocal('rf-d-company', DEFAULT_COMPANY);
  const [categories, setCategories] = useLocal('rf-d-categories', CATEGORIES);
  const [docs, setDocs] = useLocal('rf-d-docs-v3', typeof SEED_DOCS !== 'undefined' ? SEED_DOCS : []);
  const [blocked, setBlocked] = useLocal('rf-d-blocked', []);
  const [convert, setConvert] = useState(null);

  // recompute auto statuses on load
  useEffect(() => { setRentals((prev) => prev.map((r) => ({ ...r, status: autoRentalStatus(r.start, r.end) }))); }, []);

  const go = (s, params = {}) => { setScreen(s); setNav({ ...params, _t: Date.now() }); };

  const onConvert = (email) => setConvert(email);
  const createFromEmail = (r) => { setRentals((prev) => [r, ...prev]); setConvert(null); go('rentals', { rentalId: r.id }); };

  const reqCount = useMemo(() => window.withParsed(window.SEED_EMAILS).filter((m) => !m.archived && m.kind === 'request').length, []);
  const activeCount = rentals.filter((r) => r.status === 'aktiv').length;

  const navBadge = { rentals: activeCount, inbox: reqCount };

  return (
    <ThemeContext.Provider value={theme}>
      <ToastHost>
        <div style={{ display: 'flex', height: '100%', width: '100%', minHeight: 0, minWidth: 0, overflow: 'hidden', background: theme.bg, color: theme.text }}>
          {/* Sidebar */}
          <div style={{ width: 232, flexShrink: 0, display: 'flex', flexDirection: 'column', background: theme.sidebar, backdropFilter: 'blur(30px) saturate(180%)', WebkitBackdropFilter: 'blur(30px) saturate(180%)', borderRight: `0.5px solid ${theme.sep}` }}>
            {/* sidebar header */}
            <div style={{ height: 52, display: 'flex', alignItems: 'center', padding: '0 18px', WebkitAppRegion: 'drag' }}>
              <div style={{ fontSize: 14, fontWeight: 700, color: theme.text, letterSpacing: -0.3 }}>RentFlow</div>
            </div>

            <div style={{ flex: 1, overflow: 'auto', padding: '8px 12px' }}>
              <div style={{ fontSize: 10.5, color: theme.textSec, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.6, padding: '8px 10px 6px' }}>Verwaltung</div>
              {NAV.map((n) => {
                const sel = screen === n.id;
                return (
                  <Pressable key={n.id} onClick={() => go(n.id)} scale={0.99} hoverBg={sel ? undefined : theme.chip} style={{ borderRadius: 8, marginBottom: 1 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '8px 10px', borderRadius: 8, background: sel ? theme.text : 'transparent' }}>
                      <Icon d={n.icon} color={sel ? (theme.dark ? '#0a0a0a' : '#fff') : theme.textSec} size={17} sw={sel ? 2 : 1.8}/>
                      <span style={{ flex: 1, fontSize: 13.5, fontWeight: sel ? 600 : 500, color: sel ? (theme.dark ? '#0a0a0a' : '#fff') : theme.text }}>{n.label}</span>
                    </div>
                  </Pressable>
                );
              })}
            </div>

            {/* footer: profile + theme */}
            <div style={{ padding: 12, borderTop: `0.5px solid ${theme.sep}` }}>
              <Pressable onClick={() => go('profile')} scale={0.99} hoverBg={theme.chip} style={{ borderRadius: 10 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '7px 8px', borderRadius: 10, background: screen === 'profile' ? theme.chip : 'transparent' }}>
                  <div style={{ width: 34, height: 34, borderRadius: 17, background: theme.chipStrong, display: 'flex', alignItems: 'center', justifyContent: 'center', color: theme.text, fontWeight: 700, fontSize: 13 }}>{initials(company.owner)}</div>
                  <div style={{ flex: 1, minWidth: 0 }}><div style={{ fontSize: 13, fontWeight: 600, color: theme.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{company.owner}</div><div style={{ fontSize: 11, color: theme.textSec, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{company.name}</div></div>
                  <Icon d={icons.settings} color={theme.textSec} size={15} sw={1.8}/>
                </div>
              </Pressable>
            </div>
          </div>

          {/* Main content */}
          <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', background: theme.card }}>
            {screen === 'dashboard' && <ScreenDashboard go={go} equipment={equipment} rentals={rentals} events={events} tasks={tasks} setTasks={setTasks} dark={dark} toggleDark={() => setDark((v) => !v)}/>}
            {screen === 'rentals' && <ScreenRentals go={go} nav={nav} equipment={equipment} rentals={rentals} setRentals={setRentals} docs={docs} setDocs={setDocs} company={company} blocked={blocked} setBlocked={setBlocked}/>}
            {screen === 'calendar' && <ScreenCalendar go={go} equipment={equipment} rentals={rentals} setRentals={setRentals} events={events} setEvents={setEvents}/>}
            {screen === 'equipment' && <ScreenEquipment go={go} nav={nav} equipment={equipment} setEquipment={setEquipment} categories={categories} setCategories={setCategories} rentals={rentals}/>}
            {screen === 'finance' && <ScreenFinance go={go} rentals={rentals} equipment={equipment}/>}
            {screen === 'inbox' && <ScreenInbox go={go} equipment={equipment} rentals={rentals} onConvert={onConvert}/>}
            {screen === 'documents' && <ScreenDocuments go={go} nav={nav} rentals={rentals} equipment={equipment} company={company} docs={docs} setDocs={setDocs}/>}
            {screen === 'profile' && <ScreenProfile company={company} setCompany={setCompany} dark={dark} toggleDark={() => setDark((v) => !v)} data={{
              equipment, setEquipment, rentals, setRentals, events, setEvents,
              tasks, setTasks, categories, setCategories, docs, setDocs, blocked, setBlocked,
            }}/>}
          </div>
        </div>

        <ConvertSheet open={!!convert} email={convert} equipment={equipment} onClose={() => setConvert(null)} onCreate={createFromEmail}/>
      </ToastHost>
    </ThemeContext.Provider>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
