/* ═══════════════════════════════════════════════════════════════
   bezirklive.at — Geschäftsprofil-Screen
   Gewerbe-User richten hier ihre öffentliche Geschäftsseite ein:
   Logo, Kategorie, Adresse, Öffnungszeiten, Kontakt.
   ═══════════════════════════════════════════════════════════════ */

function BusinessProfileScreen({onBack}){
  const state = window._appState;
  const A = window.AppStore.actions;
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [uploadingLogo, setUploadingLogo] = useState(false);
  const logoRef = useRef(null);

  const [biz, setBiz] = useState({
    name:'', category:'', description:'', logo_url:'',
    address:'', plz: state.me.plz || '', bezirk: state.me.bezirk || '',
    phone:'', website:'', email:'', uid_number:'',
    hours: { mo:'', di:'', mi:'', do:'', fr:'', sa:'', so:'' },
  });

  const CATEGORIES = [
    {k:'gastro', l:'Gastronomie', i:'🍽️'},
    {k:'baeckerei', l:'Bäckerei', i:'🥐'},
    {k:'cafe', l:'Café', i:'☕'},
    {k:'einzelhandel', l:'Einzelhandel', i:'🛍️'},
    {k:'friseur', l:'Friseur / Beauty', i:'💈'},
    {k:'handwerk', l:'Handwerk', i:'🔧'},
    {k:'gesundheit', l:'Gesundheit', i:'⚕️'},
    {k:'dienstleistung', l:'Dienstleistung', i:'💼'},
    {k:'sonstiges', l:'Sonstiges', i:'🏪'},
  ];

  // Bestehendes Profil laden
  useEffect(() => {
    (async () => {
      if (!window.BL?.user || !window.BL.client){ setLoading(false); return; }
      try {
        const { data } = await window.BL.client.from('business_profiles')
          .select('*').eq('owner_id', window.BL.user.id).maybeSingle();
        if (data){
          setBiz(b => ({ ...b, ...data, hours: data.hours || b.hours }));
        }
      } catch(e){ console.warn('[biz] load', e); }
      setLoading(false);
    })();
  }, []);

  async function handleLogo(file){
    if (!file || !file.type.startsWith('image/')) return;
    if (file.size > 3*1024*1024){ alert('Bitte ein Logo unter 3 MB.'); return; }
    setUploadingLogo(true);
    try {
      const dataUrl = await new Promise((res,rej)=>{ const r=new FileReader(); r.onload=e=>res(e.target.result); r.onerror=rej; r.readAsDataURL(file); });
      setBiz(b => ({ ...b, logo_url: dataUrl }));
      if (window.BL?.user && window.BL.uploadDataURL){
        const url = await window.BL.uploadDataURL('logos', dataUrl);
        setBiz(b => ({ ...b, logo_url: url }));
      }
    } catch(e){ alert('Logo-Upload fehlgeschlagen.'); }
    finally { setUploadingLogo(false); }
  }

  async function save(){
    if (!biz.name.trim()){ alert('Bitte gib einen Geschäftsnamen ein.'); return; }
    setSaving(true);
    try {
      if (window.BL?.user && window.BL.client){
        const payload = {
          owner_id: window.BL.user.id,
          name: biz.name.trim(), category: biz.category, description: biz.description,
          logo_url: /^https?:/.test(biz.logo_url) ? biz.logo_url : null,
          address: biz.address, plz: biz.plz, bezirk: biz.bezirk,
          phone: biz.phone, website: biz.website, email: biz.email,
          uid_number: biz.uid_number, hours: biz.hours,
        };
        const { error } = await window.BL.client.from('business_profiles')
          .upsert(payload, { onConflict: 'owner_id' });
        if (error) throw error;
      }
      A.updateMe({ businessName: biz.name.trim() });
      alert('✓ Geschäftsprofil gespeichert!');
      onBack();
    } catch(e){ alert('Speichern fehlgeschlagen: ' + (e.message||'')); }
    finally { setSaving(false); }
  }

  const isPaid = ['basic','pro','premium'].includes(state.me.tier);

  if (loading){
    return (
      <div style={{flex:1, display:'flex', alignItems:'center', justifyContent:'center', background:T.bg}}>
        <div style={{fontSize:13, color:T.sec, fontWeight:600}}>Lade Geschäftsprofil…</div>
      </div>
    );
  }

  return (
    <div className="aIn" style={{flex:1, overflowY:'auto', background:T.bg, paddingBottom:30}}>
      {/* Header */}
      <div style={{position:'sticky', top:0, zIndex:10, background:'rgba(246,244,239,.95)', backdropFilter:'blur(10px)', padding:'12px 14px', display:'flex', alignItems:'center', gap:11}}>
        <button onClick={onBack} style={{width:34, height:34, borderRadius:10, background:'#fff', border:`1px solid ${T.bdr}`, fontSize:16, cursor:'pointer'}}>‹</button>
        <div style={{fontFamily:'Fraunces, serif', fontSize:20, fontWeight:700, letterSpacing:'-.4px'}}>Geschäftsprofil</div>
      </div>

      <div style={{padding:'14px 20px'}}>
        {!isPaid && (
          <div style={{padding:'14px 16px', background:T.goldL, border:`1px solid ${T.gold}33`, borderRadius:13, marginBottom:18}}>
            <div style={{fontSize:12.5, color:T.gold, fontWeight:700, lineHeight:1.5}}>
              ✦ Geschäftsprofile sind Teil von <strong>Premium</strong>. Du kannst dein Profil schon vorbereiten — sichtbar wird es mit einem Gewerbe-Abo.
            </div>
          </div>
        )}

        {/* Logo + Name */}
        <div style={{display:'flex', gap:14, alignItems:'center', marginBottom:20}}>
          <div onClick={()=>!uploadingLogo && logoRef.current?.click()} style={{position:'relative', cursor:'pointer', flexShrink:0}}>
            {biz.logo_url ? (
              <img src={biz.logo_url} alt="" style={{width:76, height:76, borderRadius:18, objectFit:'cover', border:`1px solid ${T.bdr}`, background:'#fff'}}/>
            ) : (
              <div style={{width:76, height:76, borderRadius:18, background:'#fff', border:`1.5px dashed ${T.bdr}`, display:'flex', alignItems:'center', justifyContent:'center', fontSize:26}}>🏪</div>
            )}
            <div style={{position:'absolute', bottom:-4, right:-4, width:26, height:26, borderRadius:'50%', background: uploadingLogo?T.muted:T.green, color:'#fff', display:'flex', alignItems:'center', justifyContent:'center', border:'2px solid #fff', fontSize:12}}>{uploadingLogo?'⏳':'📷'}</div>
            <input ref={logoRef} type="file" accept="image/*" style={{display:'none'}} onChange={e=>{ handleLogo(e.target.files[0]); e.target.value=''; }}/>
          </div>
          <div style={{flex:1, minWidth:0}}>
            <div style={{fontSize:11, fontWeight:700, color:T.sec, marginBottom:5, letterSpacing:'.2px'}}>LOGO & NAME</div>
            <Input value={biz.name} onChange={v=>setBiz({...biz, name:v})} placeholder="z.B. Café Sonnenschein" max={60}/>
          </div>
        </div>

        {/* Kategorie */}
        <div style={{fontSize:12, fontWeight:700, color:T.sec, marginBottom:8, letterSpacing:'.2px'}}>KATEGORIE</div>
        <div style={{display:'flex', flexWrap:'wrap', gap:6, marginBottom:18}}>
          {CATEGORIES.map(c=>(
            <button key={c.k} onClick={()=>setBiz({...biz, category:c.k})} style={{
              padding:'8px 11px', borderRadius:9, border:`1.5px solid ${biz.category===c.k?T.green:T.bdr}`,
              background: biz.category===c.k?T.greenL:'#fff', cursor:'pointer',
              color: biz.category===c.k?T.green:T.text, fontSize:12.5, fontWeight:700, fontFamily:'inherit',
              display:'inline-flex', alignItems:'center', gap:5,
            }}>{c.i} {c.l}</button>
          ))}
        </div>

        <Input label="Beschreibung" value={biz.description} onChange={v=>setBiz({...biz, description:v})} multiline rows={3} max={300} placeholder="Was macht dein Geschäft besonders?"/>

        {/* Adresse */}
        <div style={{fontSize:12, fontWeight:800, color:T.sec, margin:'8px 0 10px', letterSpacing:'.4px'}}>STANDORT</div>
        <Input label="Adresse" value={biz.address} onChange={v=>setBiz({...biz, address:v})} placeholder="Straße & Hausnummer"/>
        <div style={{display:'grid', gridTemplateColumns:'1fr 2fr', gap:8}}>
          <Input label="PLZ" value={biz.plz} onChange={v=>setBiz({...biz, plz:v})} placeholder="2460" max={4}/>
          <Input label="Ort / Bezirk" value={biz.bezirk} onChange={v=>setBiz({...biz, bezirk:v})} placeholder="Bruck an der Leitha"/>
        </div>

        {/* Öffnungszeiten */}
        <div style={{fontSize:12, fontWeight:800, color:T.sec, margin:'8px 0 10px', letterSpacing:'.4px'}}>ÖFFNUNGSZEITEN</div>
        <div style={{background:'#fff', border:`1px solid ${T.bdr}`, borderRadius:12, padding:'8px 12px', marginBottom:18}}>
          {[['mo','Montag'],['di','Dienstag'],['mi','Mittwoch'],['do','Donnerstag'],['fr','Freitag'],['sa','Samstag'],['so','Sonntag']].map(([k,l])=>(
            <div key={k} style={{display:'flex', alignItems:'center', gap:10, padding:'6px 0', borderBottom: k!=='so'?`1px solid ${T.sep}`:'none'}}>
              <div style={{fontSize:12.5, fontWeight:700, color:T.text, width:90}}>{l}</div>
              <input
                value={biz.hours[k]||''}
                onChange={e=>setBiz({...biz, hours:{...biz.hours, [k]:e.target.value}})}
                placeholder="z.B. 08:00–18:00 oder Geschlossen"
                style={{flex:1, padding:'7px 10px', borderRadius:8, border:`1px solid ${T.bdr}`, background:T.bg, fontSize:12.5, fontFamily:'inherit', color:T.text, outline:'none'}}
              />
            </div>
          ))}
        </div>

        {/* Kontakt */}
        <div style={{fontSize:12, fontWeight:800, color:T.sec, margin:'8px 0 10px', letterSpacing:'.4px'}}>KONTAKT</div>
        <Input label="Telefon" value={biz.phone} onChange={v=>setBiz({...biz, phone:v})} placeholder="+43 …" type="tel"/>
        <Input label="Website" value={biz.website} onChange={v=>setBiz({...biz, website:v})} placeholder="https://…"/>
        <Input label="E-Mail" value={biz.email} onChange={v=>setBiz({...biz, email:v})} placeholder="kontakt@…" type="email"/>
        <Input label="UID-Nummer (optional)" value={biz.uid_number} onChange={v=>setBiz({...biz, uid_number:v})} placeholder="ATU12345678"/>

        <div style={{marginTop:18}}>
          <Btn full kind="primary" size="lg" disabled={saving} onClick={save}>{saving ? 'Speichert…' : '✓ Geschäftsprofil speichern'}</Btn>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { BusinessProfileScreen });
