// Mieter screens
const MieterDashboard = ({onNav, ctx}) => {
  const session = ctx?.session;
  const firstName = session?.name?.split(' ')[0] || 'Mieter';
  const [tickets, setTickets] = React.useState([]);
  const now = new Date();
  const dateStr = now.toLocaleDateString('de-CH', {weekday:'long', day:'numeric', month:'long', year:'numeric'});

  React.useEffect(() => {
    Store.getTickets().then(setTickets);
  }, [ctx?.dataTick]);

  const myTickets = tickets.filter(t => t.status !== 'erledigt');

  return (
    <>
      <PageHeader
        eyebrow={`§ Ihre Wohnung · ${dateStr}`}
        title={`Willkommen, ${firstName}`}
        sub={session?.unit
          ? `${session.unit}${session?.prop_id ? ' · ' + session.prop_id : ''}`
          : 'Ihre Mietwohnung bei ImmoHub Schweiz'}
      />
      <div className="pagebody">
        <div className="mieter-hero mb-16">
          <div className="flex justify-between items-start">
            <div style={{zIndex:2, position:'relative'}}>
              <div className="page-eyebrow" style={{color:'rgba(255,255,255,0.55)'}}>IHRE WOHNUNG</div>
              <h2 className="mt-8">{session?.unit || 'Ihre Wohnung'}</h2>
              <div className="addr mt-8">{session?.email}</div>
              <div className="flex gap-8 mt-16" style={{zIndex:2, position:'relative'}}>
                <Badge tone="ok" dot={false}>Vertrag aktiv</Badge>
              </div>
            </div>
          </div>
        </div>

        <div className="grid-4 mb-16">
          <button className="quick-tile red" onClick={()=>onNav('meldung-neu')}>
            <span className="qt-ic"><Icon name="alert" size={16}/></span>
            <span className="qt-t">Schaden melden</span>
            <span className="qt-s">Sanitär, Elektro, Schimmel …</span>
          </button>
          <button className="quick-tile" onClick={()=>onNav('chat')}>
            <span className="qt-ic"><Icon name="chat" size={16}/></span>
            <span className="qt-t">Verwaltung kontaktieren</span>
            <span className="qt-s">Chat mit Verwaltung & Hauswart</span>
          </button>
          <button className="quick-tile" onClick={()=>onNav('wasch')}>
            <span className="qt-ic"><Icon name="washer" size={16}/></span>
            <span className="qt-t">Waschküche buchen</span>
            <span className="qt-s">Verfügbare Slots anzeigen</span>
          </button>
          <button className="quick-tile" onClick={()=>onNav('docs')}>
            <span className="qt-ic"><Icon name="doc" size={16}/></span>
            <span className="qt-t">Meine Dokumente</span>
            <span className="qt-s">Miet­vertrag, NK-Abrechnung …</span>
          </button>
        </div>

        <div className="grid-dash">
          <div className="v-stack gap-16">
            <Card title="Meine Meldungen" action={<Button size="sm" onClick={()=>onNav('meldung-neu')} leftIcon="plus">Neu</Button>}>
              {myTickets.length === 0 ? (
                <div style={{padding:'24px 0', textAlign:'center', color:'var(--ink-400)', fontSize:13}}>
                  Keine offenen Meldungen. <button className="link-btn" onClick={()=>onNav('meldung-neu')}>Neue Meldung erstellen</button>
                </div>
              ) : (
                <div className="v-stack gap-12">
                  {myTickets.slice(0,3).map(t=>(
                    <div key={t.id} style={{padding:14, border:'1px solid var(--ink-200)', borderRadius:4}}>
                      <div className="flex justify-between items-center">
                        <div><span className="mono text-xs text-muted">{t.id}</span> <span style={{fontWeight:500, fontSize:13, marginLeft:8}}>{t.title}</span></div>
                        <StatusBadge status={t.status}/>
                      </div>
                      <div className="mt-12"><MeldungPipe status={t.status}/></div>
                      <div className="flex justify-between text-xs text-muted mt-8">
                        <span>{t.category}</span>
                        <span className="font-mono">{t.created_at ? new Date(t.created_at).toLocaleDateString('de-CH') : ''}</span>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </Card>
          </div>

          <div className="v-stack gap-16">
            <Card title="Konto">
              {[['Name', session?.name], ['E-Mail', session?.email], ['Rolle', 'Mieter'], ['Einheit', session?.unit || '—']].map(([k,v])=>(
                <div key={k} style={{padding:'8px 0', borderBottom:'1px solid var(--ink-150)', display:'flex', justifyContent:'space-between'}}>
                  <span className="text-xs text-muted">{k}</span>
                  <span style={{fontSize:13}}>{v||'—'}</span>
                </div>
              ))}
            </Card>
          </div>
        </div>
      </div>
    </>
  );
};

const MeldungPipe = ({status}) => {
  const steps = ['neu','gesichtet','auftrag','termin','erledigt'];
  const cur = STATUS_LABELS[status]?.idx ?? 0;
  const labels = {neu:'Gemeldet', gesichtet:'Gesichtet', auftrag:'Auftrag', termin:'Termin', erledigt:'Erledigt'};
  return (
    <div className="pipe">
      {steps.map((s,i)=>(
        <div key={s} className={`pipe-step ${i<cur?'done':''} ${i===cur?'active':''}`}>
          <div className="pipe-d"/>
          <div className="l">{labels[s]}</div>
        </div>
      ))}
    </div>
  );
};

const MeldungNeu = ({onDone, ctx}) => {
  const [step, setStep] = React.useState(0);
  const [cat, setCat] = React.useState('Sanitär');
  const [urg, setUrg] = React.useState('normal');
  const [title, setTitle] = React.useState('');
  const [desc, setDesc] = React.useState('');
  const [ticketId, setTicketId] = React.useState('');
  const [submitting, setSubmitting] = React.useState(false);

  const cats = [
    {k:'Sanitär',ic:'sanitar'},{k:'Elektro',ic:'electro'},{k:'Fenster/Türen',ic:'door'},
    {k:'Heizung',ic:'heat'},{k:'Schimmel',ic:'mold'},{k:'Geräte',ic:'device'},
    {k:'Allgemeinbereich',ic:'cube'},{k:'Sonstiges',ic:'cube'}
  ];

  const submit = async () => {
    if (!title || submitting) return;
    setSubmitting(true);
    try {
      const t = await Store.createTicket({
        title,
        description: desc,
        category: cat,
        urgency: urg,
        unit: ctx?.session?.unit || '',
        propId: ctx?.session?.prop_id || null,
      });
      setTicketId(t.id);
      setStep(2);
    } catch(e) {
      alert(e.message);
    }
    setSubmitting(false);
  };

  return (
    <>
      <PageHeader
        eyebrow={<><a style={{cursor:'pointer'}} onClick={()=>onDone()}>Dashboard</a> / Neue Meldung</>}
        title="Schaden melden"
        sub="Eingang: Verwaltung & Hauswart werden sofort benachrichtigt. Sie erhalten eine Ticket-Nummer."
      />
      <div className="pagebody" style={{maxWidth:820}}>
        {step===0 && (
          <div className="card">
            <div className="card-body">
              <div className="text-xs text-muted font-mono mb-8">SCHRITT 1 VON 3</div>
              <h3 style={{fontSize:18, margin:'0 0 18px', fontWeight:500, letterSpacing:'-0.02em'}}>Um welche Art Schaden handelt es sich?</h3>
              <div className="grid-4" style={{gap:10}}>
                {cats.map(c=>(
                  <button key={c.k} onClick={()=>setCat(c.k)} style={{
                    padding:18, background:cat===c.k?'var(--ink-900)':'var(--white)',
                    color:cat===c.k?'#fff':'var(--ink-900)',
                    border:'1px solid '+(cat===c.k?'var(--ink-900)':'var(--ink-200)'),
                    borderRadius:4, cursor:'pointer', textAlign:'left'
                  }}>
                    <Icon name={c.ic} size={22} stroke={1.5}/>
                    <div style={{fontSize:13, fontWeight:500, marginTop:10}}>{c.k}</div>
                  </button>
                ))}
              </div>
              <div className="flex justify-end mt-24">
                <Button variant="primary" rightIcon="arrow-right" onClick={()=>setStep(1)}>Weiter</Button>
              </div>
            </div>
          </div>
        )}
        {step===1 && (
          <div className="card"><div className="card-body">
            <div className="text-xs text-muted font-mono mb-8">SCHRITT 2 VON 3</div>
            <h3 style={{fontSize:18, margin:'0 0 18px', fontWeight:500, letterSpacing:'-0.02em'}}>Beschreibung</h3>
            <div className="field">
              <label>Kurz­beschreibung *</label>
              <input className="input" value={title} onChange={e=>setTitle(e.target.value)} placeholder="z.B. Wasserhahn tropft, Heizung kalt…"/>
            </div>
            <div className="field">
              <label>Details · Was ist passiert, seit wann?</label>
              <textarea className="textarea" value={desc} onChange={e=>setDesc(e.target.value)} placeholder="Beschreiben Sie das Problem genau. Seit wann besteht es?" style={{minHeight:100}}/>
            </div>
            <div className="field">
              <label>Dringlichkeit</label>
              <div className="flex gap-8 mt-4">
                {['normal','dringend'].map(u=>(
                  <button key={u} onClick={()=>setUrg(u)} style={{
                    flex:1, padding:'12px 14px', borderRadius:4,
                    border:'1px solid '+(urg===u?'var(--ink-900)':'var(--ink-200)'),
                    background:urg===u?'var(--ink-900)':'var(--white)',
                    color:urg===u?'#fff':'var(--ink-900)', textAlign:'left', cursor:'pointer'
                  }}>
                    <div style={{fontWeight:500, fontSize:13}}>{URGENCY[u].l}</div>
                    <div className="text-xs" style={{opacity:0.7, marginTop:2}}>
                      {u==='normal'?'Innerhalb einer Woche':'Innerhalb 48 Stunden'}
                    </div>
                  </button>
                ))}
              </div>
            </div>
            <div className="flex justify-between mt-24">
              <Button variant="ghost" leftIcon="chevron-left" onClick={()=>setStep(0)}>Zurück</Button>
              <Button variant="primary" rightIcon="arrow-right" onClick={submit} disabled={!title||submitting}>
                {submitting ? 'Wird gesendet…' : 'Meldung absenden'}
              </Button>
            </div>
          </div></div>
        )}
        {step===2 && (
          <div className="card"><div className="card-body text-center" style={{padding:'40px 24px'}}>
            <div style={{width:56, height:56, background:'#E7F3EC', borderRadius:'50%', margin:'0 auto 18px', display:'flex', alignItems:'center', justifyContent:'center', color:'var(--ok-ink)'}}>
              <Icon name="check" size={28}/>
            </div>
            <div className="text-xs text-muted font-mono">MELDUNG ERHALTEN</div>
            <h2 style={{fontSize:22, fontWeight:500, letterSpacing:'-0.02em', margin:'6px 0'}}>Ticket {ticketId} erstellt</h2>
            <div className="text-sm text-muted">Die Verwaltung wurde benachrichtigt und meldet sich innerhalb 24 Std.</div>
            <div className="hairline"/>
            <MeldungPipe status="neu"/>
            <div className="flex justify-center gap-8 mt-24">
              <Button onClick={()=>onDone()}>Zum Dashboard</Button>
              <Button variant="primary" leftIcon="chat" onClick={()=>onDone('chat')}>Mit Verwaltung chatten</Button>
            </div>
          </div></div>
        )}
      </div>
    </>
  );
};

Object.assign(window, {MieterDashboard, MeldungNeu, MeldungPipe});
