// App — async session init, API-backed auth
const NAV = {
  verwaltung: [
    {section:'ARBEITSBEREICH'},
    {k:'dashboard',icon:'dashboard',l:'Dashboard'},
    {k:'liegenschaften',icon:'building',l:'Liegenschaften'},
    {k:'meldungen',icon:'alert',l:'Schadens­meldungen',count:'12',dot:true},
    {k:'wartung',icon:'wrench',l:'Wartungs­aufträge',count:'4'},
    {section:'KOMMUNIKATION'},
    {k:'chat',icon:'chat',l:'Chat',count:'3'},
    {k:'news',icon:'pin',l:'Schwarzes Brett'},
    {k:'kalender',icon:'calendar',l:'Kalender'},
    {section:'ADMINISTRATION'},
    {k:'docs',icon:'doc',l:'Dokumente'},
    {k:'mieter',icon:'users',l:'Mieter & Einladungen'},
    {k:'einstellungen',icon:'settings',l:'Einstellungen'},
  ],
  mieter: [
    {section:'IHRE WOHNUNG'},
    {k:'dashboard',icon:'home',l:'Übersicht'},
    {k:'meldungen',icon:'alert',l:'Meine Meldungen',count:'2'},
    {k:'docs',icon:'doc',l:'Meine Dokumente'},
    {section:'LIEGENSCHAFT'},
    {k:'chat',icon:'chat',l:'Liegenschafts-Chat',count:'11'},
    {k:'news',icon:'pin',l:'Schwarzes Brett',dot:true},
    {k:'kalender',icon:'calendar',l:'Termine'},
    {k:'wasch',icon:'washer',l:'Waschküche'},
    {section:'KONTO'},
    {k:'einstellungen',icon:'settings',l:'Einstellungen'},
  ],
  hauswart: [
    {section:'ARBEITSBEREICH'},
    {k:'dashboard',icon:'dashboard',l:'Heute'},
    {k:'meldungen',icon:'alert',l:'Meldungen',count:'2'},
    {k:'wartung',icon:'wrench',l:'Aufträge',count:'6'},
    {k:'kalender',icon:'calendar',l:'Kalender'},
    {section:'LIEGENSCHAFTEN'},
    {k:'liegenschaften',icon:'building',l:'Meine Liegenschaften',count:'4'},
    {k:'chat',icon:'chat',l:'Chats',count:'4'},
    {section:'KONTO'},
    {k:'einstellungen',icon:'settings',l:'Einstellungen'},
  ],
};

const TONE = {verwaltung:'red', mieter:'gold', hauswart:'green'};

const LoadingScreen = () => (
  <div style={{minHeight:'100vh',display:'flex',alignItems:'center',justifyContent:'center',background:'var(--paper)'}}>
    <div style={{textAlign:'center'}}>
      <Icon name="logo-cross" size={32}/>
      <div className="text-muted" style={{fontSize:13,marginTop:12,fontFamily:'var(--font-mono)',letterSpacing:'0.05em'}}>WIRD GELADEN…</div>
    </div>
  </div>
);

const App = () => {
  const [session, setSession] = React.useState(null);
  const [org, setOrg] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [authView, setAuthView] = React.useState('login');
  const [page, setPage] = React.useState('dashboard');
  const [propId, setPropId] = React.useState(null);
  const [dataTick, setDataTick] = React.useState(0);

  const inviteCode = React.useMemo(() => {
    const m = window.location.hash.match(/[#&]invite=([A-Z0-9]+)/i);
    return m ? m[1] : null;
  }, []);

  // Restore session from token on mount
  React.useEffect(() => {
    if (!Store.hasToken()) { setLoading(false); return; }
    Store.getMe().then(data => {
      if (data) { setSession(data.session); setOrg(data.org); }
      setLoading(false);
    });
  }, []);

  const reload = () => setDataTick(t => t + 1);

  const ctx = React.useMemo(() => {
    if (!session) return null;
    return { session, org, reload, dataTick };
  }, [session, org, dataTick]);

  const handleLogin = (sess) => {
    setSession(sess);
    setPage('dashboard');
    window.location.hash = '';
    Store.getMe().then(d => { if (d) setOrg(d.org); });
  };

  const handleLogout = async () => {
    await Store.logout();
    setSession(null); setOrg(null); setPage('dashboard');
  };

  const navigate = (p, arg) => {
    setPage(p);
    if (p === 'liegenschaft' && arg) setPropId(arg);
  };

  if (loading) return <LoadingScreen/>;

  // Invite flow
  if (inviteCode && !session) return (
    <div className="app" style={{display:'block'}}>
      <AcceptInviteScreen code={inviteCode} onSuccess={handleLogin}/>
    </div>
  );

  // Auth flow
  if (!session) return (
    <div className="app" style={{display:'block'}}>
      {authView==='login'
        ? <LoginScreen onSuccess={handleLogin} onRegister={()=>setAuthView('register')}/>
        : <RegisterScreen onSuccess={handleLogin} onLogin={()=>setAuthView('login')}/>}
    </div>
  );

  const role = session.role;

  const renderPage = () => {
    if (role==='verwaltung') {
      if (page==='dashboard')     return <VerwaltungDashboard onNav={navigate} ctx={ctx}/>;
      if (page==='liegenschaften')return <LiegenschaftenList onOpen={id=>navigate('liegenschaft',id)} ctx={ctx}/>;
      if (page==='liegenschaft')  return <LiegenschaftDetail propId={propId} onNav={navigate} ctx={ctx}/>;
      if (page==='meldungen')     return <MeldungenKanban onOpen={()=>{}} ctx={ctx}/>;
      if (page==='wartung')       return <><PageHeader eyebrow="§ Wartung" title="Wartungs­aufträge" sub="12 Aufträge · 4 in Arbeit"/><div className="pagebody"><WartungList/></div></>;
      if (page==='chat')          return <LiegenschaftsChat/>;
      if (page==='news')          return <SchwarzesBrett standalone/>;
      if (page==='kalender')      return <KalenderView/>;
      if (page==='docs')          return <DokumenteView/>;
      if (page==='mieter')        return <MieterListView ctx={ctx}/>;
      if (page==='einstellungen') return <EinstellungenView ctx={ctx}/>;
    }
    if (role==='mieter') {
      if (page==='dashboard')     return <MieterDashboard onNav={navigate} ctx={ctx}/>;
      if (page==='meldung-neu')   return <MeldungNeu onDone={t=>navigate(t||'dashboard')} ctx={ctx}/>;
      if (page==='meldungen')     return <MieterMeldungen onNav={navigate}/>;
      if (page==='chat')          return <LiegenschaftsChat/>;
      if (page==='news')          return <SchwarzesBrett standalone/>;
      if (page==='kalender')      return <KalenderView/>;
      if (page==='wasch')         return <WaschkueheView/>;
      if (page==='docs')          return <MieterDocs/>;
      if (page==='einstellungen') return <EinstellungenView ctx={ctx}/>;
    }
    if (role==='hauswart') {
      if (page==='dashboard')     return <HauswartDashboard onNav={navigate} ctx={ctx}/>;
      if (page==='meldungen')     return <MeldungenKanban onOpen={()=>{}} ctx={ctx}/>;
      if (page==='wartung')       return <><PageHeader eyebrow="§ Aufträge" title="Meine Aufträge" sub="6 Aufgaben · Foto­protokoll pro Erledigung"/><div className="pagebody"><WartungList/></div></>;
      if (page==='chat')          return <LiegenschaftsChat/>;
      if (page==='kalender')      return <KalenderView/>;
      if (page==='liegenschaften')return <LiegenschaftenList onOpen={id=>navigate('liegenschaft',id)} ctx={ctx}/>;
      if (page==='einstellungen') return <EinstellungenView ctx={ctx}/>;
    }
    return null;
  };

  const nav = NAV[role] || [];

  return (
    <div className="app">
      <header className="topbar">
        <div className="topbar-inner">
          <div className="topbar-brand"><Icon name="logo-cross"/><div className="brand-wm">ImmoHub<sup>Schweiz</sup></div></div>
          <div className="topbar-nav">
            <button className="is-active">Workspace</button>
            <button>Changelog</button>
            <button>Hilfe</button>
          </div>
          <div className="topbar-right">
            <div className="hosted-chip"><span className="dot"/><Icon name="flag-ch" size={12}/><span>Interxion Zürich · All systems OK</span></div>
            {org && <div style={{fontSize:12,color:'var(--ink-500)',fontFamily:'var(--font-mono)'}}>{org.name}</div>}
            <div style={{display:'flex',alignItems:'center',gap:8}}>
              <Avatar initials={session.initials||'??'} tone={TONE[role]||'red'} size="md"/>
              <div style={{fontSize:12}}>
                <div style={{fontWeight:500}}>{session.name}</div>
                <div className="text-muted" style={{fontSize:11,textTransform:'capitalize'}}>{role}</div>
              </div>
              <button className="btn btn-ghost btn-sm" onClick={handleLogout} title="Abmelden"><Icon name="logout" size={14}/></button>
            </div>
          </div>
        </div>
      </header>
      <div className="main">
        <aside className="sidebar">
          {nav.map((n,i) => {
            if (n.section) return <div key={i} className="sb-section">{n.section}</div>;
            return <SidebarItem key={n.k} icon={n.icon} label={n.l} count={n.count} dot={n.dot} active={page===n.k} onClick={()=>navigate(n.k)}/>;
          })}
          <div className="sb-foot">
            <div className="flex gap-4 items-center" style={{fontSize:10,color:'var(--ink-500)',fontFamily:'var(--font-mono)',letterSpacing:'0.04em'}}>
              <Icon name="flag-ch" size={10}/> HOSTED IN CH · v1.0
            </div>
          </div>
        </aside>
        <main className="content">{renderPage()}</main>
      </div>
    </div>
  );
};

// Mieter list with async invite system
const MieterListView = ({ ctx }) => {
  const [users, setUsers] = React.useState([]);
  const [pending, setPending] = React.useState([]);
  const [props, setProps] = React.useState([]);
  const [showModal, setShowModal] = React.useState(false);
  const [form, setForm] = React.useState({name:'',email:'',role:'mieter',propId:'',unit:''});
  const [genLink, setGenLink] = React.useState('');
  const [copied, setCopied] = React.useState(false);
  const [loadingInvite, setLoadingInvite] = React.useState(false);

  const upd = (k,v) => setForm(f=>({...f,[k]:v}));

  const fetchData = () => {
    Store.getUsers().then(setUsers);
    Store.getPendingInvites().then(setPending);
    Store.getProperties().then(setProps);
  };

  React.useEffect(fetchData, [ctx.dataTick]);

  const nonAdmin = users.filter(u => u.role !== 'verwaltung');

  const sendInvite = async () => {
    if (!form.email||loadingInvite) return;
    setLoadingInvite(true);
    try {
      const inv = await Store.createInvite(form);
      const link = window.location.origin + window.location.pathname + '#invite=' + inv.code;
      setGenLink(link);
      fetchData();
    } catch(e) { alert(e.message); }
    setLoadingInvite(false);
  };

  const copyLink = (link) => {
    navigator.clipboard.writeText(link).then(()=>{ setCopied(true); setTimeout(()=>setCopied(false),2000); });
  };

  const closeModal = () => { setShowModal(false); setForm({name:'',email:'',role:'mieter',propId:'',unit:''}); setGenLink(''); };

  return (
    <>
      <PageHeader eyebrow="§ Nutzer" title="Mieter & Einladungen" sub={`${nonAdmin.length} aktive Nutzer · ${pending.length} ausstehende Einladungen`} actions={<Button variant="primary" leftIcon="plus" onClick={()=>setShowModal(true)}>Einladen</Button>}/>
      <div className="pagebody">
        {nonAdmin.length > 0 && (
          <Card title="Aktive Nutzer" style={{marginBottom:16}}>
            <table className="tbl">
              <thead><tr><th></th><th>Name</th><th>E-Mail</th><th>Rolle</th><th>Einheit</th><th>Seit</th></tr></thead>
              <tbody>
                {nonAdmin.map(u=>(
                  <tr key={u.id}>
                    <td style={{width:40}}><Avatar initials={u.initials||u.name?.slice(0,2)||'?'} tone={u.role==='hauswart'?'green':'gold'} size="lg"/></td>
                    <td><div style={{fontWeight:500}}>{u.name}</div></td>
                    <td style={{color:'var(--ink-500)',fontSize:13}}>{u.email}</td>
                    <td><RoleBadge role={u.role}/></td>
                    <td className="font-mono text-xs">{u.unit||'—'}</td>
                    <td className="font-mono text-xs">{u.created_at ? new Date(u.created_at).toLocaleDateString('de-CH') : '—'}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </Card>
        )}

        {nonAdmin.length===0 && pending.length===0 && (
          <Card><div style={{padding:'40px 0',textAlign:'center',color:'var(--ink-400)'}}>
            <Icon name="users" size={32}/>
            <div style={{marginTop:12,fontSize:14}}>Noch keine Mieter oder Hauswarte eingeladen.</div>
            <div className="text-xs text-muted mt-8">Klicken Sie auf «Einladen» um Einladungslinks zu erstellen.</div>
          </div></Card>
        )}

        {pending.length > 0 && (
          <Card title="Ausstehende Einladungen">
            <table className="tbl">
              <thead><tr><th>Name</th><th>E-Mail</th><th>Rolle</th><th>Einheit</th><th>Erstellt</th><th className="text-right">Link</th></tr></thead>
              <tbody>
                {pending.map(inv=>{
                  const link = window.location.origin+window.location.pathname+'#invite='+inv.code;
                  return (
                    <tr key={inv.code}>
                      <td style={{fontWeight:500}}>{inv.name||'—'}</td>
                      <td style={{color:'var(--ink-500)',fontSize:13}}>{inv.email}</td>
                      <td><RoleBadge role={inv.role}/></td>
                      <td className="font-mono text-xs">{inv.unit||'—'}</td>
                      <td className="font-mono text-xs">{inv.created_at ? new Date(inv.created_at).toLocaleDateString('de-CH') : '—'}</td>
                      <td className="text-right"><Button size="sm" onClick={()=>copyLink(link)}>Link kopieren</Button></td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </Card>
        )}
      </div>

      {showModal && (
        <div style={{position:'fixed',inset:0,background:'rgba(10,22,40,0.5)',zIndex:1000,display:'flex',alignItems:'center',justifyContent:'center'}} onClick={e=>e.target===e.currentTarget&&closeModal()}>
          <div style={{background:'#fff',borderRadius:8,padding:28,width:480,maxWidth:'95vw',boxShadow:'0 20px 60px rgba(0,0,0,0.25)'}}>
            <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:20}}>
              <h3 style={{fontSize:17,fontWeight:600,margin:0}}>Einladung erstellen</h3>
              <button className="btn btn-ghost btn-sm" onClick={closeModal}><Icon name="x" size={16}/></button>
            </div>
            {!genLink ? (
              <div className="v-stack gap-12">
                <div className="field-row">
                  <div className="field"><label>Name (optional)</label><input type="text" value={form.name} onChange={e=>upd('name',e.target.value)} placeholder="Vorname Nachname"/></div>
                  <div className="field"><label>E-Mail *</label><input type="email" value={form.email} onChange={e=>upd('email',e.target.value)} placeholder="name@email.ch"/></div>
                </div>
                <div className="field"><label>Rolle</label>
                  <select value={form.role} onChange={e=>upd('role',e.target.value)} style={{width:'100%',padding:'8px 10px',border:'1px solid var(--ink-200)',borderRadius:4,fontSize:13,background:'#fff'}}>
                    <option value="mieter">Mieter</option>
                    <option value="hauswart">Hauswart</option>
                    <option value="verwaltung">Verwaltung (Admin)</option>
                  </select>
                </div>
                {props.length>0 && (
                  <div className="field-row">
                    <div className="field"><label>Liegenschaft</label>
                      <select value={form.propId} onChange={e=>upd('propId',e.target.value)} style={{width:'100%',padding:'8px 10px',border:'1px solid var(--ink-200)',borderRadius:4,fontSize:13,background:'#fff'}}>
                        <option value="">— keine Zuordnung —</option>
                        {props.map(p=><option key={p.id} value={p.id}>{p.street}, {p.city}</option>)}
                      </select>
                    </div>
                    <div className="field"><label>Einheit / Wohnung</label><input type="text" value={form.unit} onChange={e=>upd('unit',e.target.value)} placeholder="z.B. 2.OG links"/></div>
                  </div>
                )}
                <div className="flex gap-8 mt-8">
                  <button className="btn btn-ghost" onClick={closeModal}>Abbrechen</button>
                  <button className="btn btn-primary btn-full" onClick={sendInvite} disabled={!form.email||loadingInvite}>
                    {loadingInvite?'Wird erstellt…':'Einladungslink generieren'}
                  </button>
                </div>
              </div>
            ) : (
              <div>
                <div style={{padding:16,background:'var(--paper)',borderRadius:6,border:'1px solid var(--ink-200)',marginBottom:16}}>
                  <div className="text-xs text-muted font-mono mb-8">EINLADUNGSLINK</div>
                  <div style={{fontSize:12,wordBreak:'break-all',color:'var(--ink-700)',fontFamily:'var(--font-mono)'}}>{genLink}</div>
                </div>
                <div style={{fontSize:13,color:'var(--ink-500)',marginBottom:16}}>Senden Sie diesen Link an <strong>{form.email}</strong>.</div>
                <div className="flex gap-8">
                  <button className="btn btn-primary btn-full" onClick={()=>copyLink(genLink)}>{copied?'✓ Kopiert!':'Link kopieren'}</button>
                  <button className="btn btn-secondary" onClick={closeModal}>Fertig</button>
                </div>
              </div>
            )}
          </div>
        </div>
      )}
    </>
  );
};

const MieterMeldungen = ({onNav}) => (
  <>
    <PageHeader eyebrow="§ Meine Meldungen" title="Schadens­meldungen" sub="Alle von Ihnen erfassten Meldungen" actions={<Button variant="danger" leftIcon="plus" onClick={()=>onNav('meldung-neu')}>Neue Meldung</Button>}/>
    <div className="pagebody"><Card><table className="tbl">
      <thead><tr><th>Ticket</th><th>Titel</th><th>Kategorie</th><th>Status</th><th>Gemeldet</th><th className="text-right"></th></tr></thead>
      <tbody>
        <tr><td className="mono">SM-0377</td><td style={{fontWeight:500}}>Kühlschrank-Dichtung</td><td>Geräte</td><td><StatusBadge status="termin"/></td><td className="mono">17.04.2026</td><td className="text-right"><Button size="sm">Öffnen</Button></td></tr>
        <tr><td className="mono">SM-0373</td><td style={{fontWeight:500}}>Wohnungstür-Scharnier</td><td>Fenster/Türen</td><td><StatusBadge status="erledigt"/></td><td className="mono">08.04.2026</td><td className="text-right"><Button size="sm">Öffnen</Button></td></tr>
      </tbody>
    </table></Card></div>
  </>
);

const MieterDocs = () => (
  <>
    <PageHeader eyebrow="§ Meine Dokumente" title="Dokumente" sub="Mietvertrag, Nebenkostenabrechnungen und allgemeine Dokumente"/>
    <div className="pagebody"><DokumenteView scope="mieter"/></div>
  </>
);

const EinstellungenView = ({ ctx }) => {
  const s = ctx?.session;
  const o = ctx?.org;
  const [team, setTeam] = React.useState([]);

  React.useEffect(() => {
    if (s?.role === 'verwaltung') Store.getUsers().then(setTeam);
  }, [s?.role]);

  return (
    <>
      <PageHeader eyebrow="§ Einstellungen" title="Konto & Einstellungen" sub="Persönliche Daten und Systemeinstellungen"/>
      <div className="pagebody"><div className="grid-dash">
        <div className="v-stack gap-16">
          <Card title="Persönliche Daten">
            {[['Name',s?.name],['E-Mail',s?.email],['Rolle',s?.role]].map(([k,v])=>(
              <div key={k} style={{padding:'10px 0',borderBottom:'1px solid var(--ink-150)',display:'flex',justifyContent:'space-between'}}>
                <span className="text-xs text-muted" style={{textTransform:'uppercase',letterSpacing:'0.05em'}}>{k}</span>
                <span style={{fontSize:13,fontWeight:500}}>{v||'—'}</span>
              </div>
            ))}
          </Card>
          {team.length > 0 && (
            <Card title="Team">
              <table className="tbl">
                <thead><tr><th></th><th>Name</th><th>E-Mail</th><th>Rolle</th><th>Seit</th></tr></thead>
                <tbody>
                  {team.map(u=>(
                    <tr key={u.id}>
                      <td style={{width:36}}><Avatar initials={u.initials||u.name?.slice(0,2)||'?'} tone={u.role==='hauswart'?'green':u.role==='verwaltung'?'red':'gold'} size="lg"/></td>
                      <td><div style={{fontWeight:500}}>{u.name}</div></td>
                      <td style={{color:'var(--ink-500)',fontSize:13}}>{u.email}</td>
                      <td><RoleBadge role={u.role}/></td>
                      <td className="font-mono text-xs">{u.created_at ? new Date(u.created_at).toLocaleDateString('de-CH') : '—'}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </Card>
          )}
        </div>
        {o && <Card title="Organisation">
          {[['Firmenname',o.name],['Plan',o.plan||'starter'],['Erstellt',o.created_at?new Date(o.created_at).toLocaleDateString('de-CH'):'—']].map(([k,v])=>(
            <div key={k} style={{padding:'10px 0',borderBottom:'1px solid var(--ink-150)',display:'flex',justifyContent:'space-between'}}>
              <span className="text-xs text-muted" style={{textTransform:'uppercase',letterSpacing:'0.05em'}}>{k}</span>
              <span style={{fontSize:13}}>{v||'—'}</span>
            </div>
          ))}
        </Card>}
      </div></div>
    </>
  );
};

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