/* ═══════════════════════════════════════════════════════════════
   bezirk.live — Shared Components & Theme
   ═══════════════════════════════════════════════════════════════ */

const { useState, useEffect, useRef, useMemo, useCallback, createContext, useContext } = React;

// ─── THEME ───────────────────────────────────────────────────────
const T = {
  bg:'#F6F4EF', card:'#FFF', text:'#0C0C0A', sec:'#66645D', muted:'#A8A59E',
  bdr:'#EBEBEA', bdrSoft:'#F2F0EC',
  green:'#0A4A24', greenL:'#E4F0E9', greenLL:'#F0F8F2',
  gold:'#B8860B', goldL:'#FFF8E1',
  care:'#2C4A7A', careL:'#EBF0FA',
  amber:'#C07B0A', amberL:'#FEF2DC',
  teal:'#0F4C44', tealL:'#D9E8E4',
  purple:'#7A4FB8', purpleL:'#F0E8F8',
  red:'#B91C1C', redL:'#FEE2E2',
  ink:'#15151A', inkSoft:'#1F1F25',
};

// ─── UTILS ───────────────────────────────────────────────────────
function timeAgo(ts){
  const d = Date.now() - ts;
  const mins = Math.floor(d/60000);
  if (mins<1) return 'gerade';
  if (mins<60) return `vor ${mins} Min`;
  const hrs = Math.floor(mins/60);
  if (hrs<24) return `vor ${hrs} Std`;
  const days = Math.floor(hrs/24);
  if (days<7) return `vor ${days} Tg`;
  return `vor ${Math.floor(days/7)} Wo`;
}

function useCountdown(expiresAt){
  const [, setTick] = useState(0);
  useEffect(()=>{
    const id = setInterval(()=>setTick(t=>t+1), 60000);
    return ()=>clearInterval(id);
  },[]);
  if (!expiresAt) return null;
  const ms = expiresAt - Date.now();
  if (ms<=0) return 'abgelaufen';
  const hrs = Math.floor(ms/3600000);
  const mins = Math.floor((ms%3600000)/60000);
  if (hrs>=24){
    const d = Math.floor(hrs/24);
    return `${d} Tg ${hrs%24}h`;
  }
  return `${hrs}h ${mins}min`;
}

function fmtPrice(n, label){
  if (label==='Gratis' || n===0) return 'Gratis';
  if (label==='Tausch') return 'Tausch';
  if (label==='Leihen') return 'Leihen';
  return '€ ' + n;
}

// ─── ATOMS ───────────────────────────────────────────────────────

function Avatar({a, size=36, border=false, name='', src=null}){
  const initials = name ? name.split(' ').map(s=>s[0]).slice(0,2).join('').toUpperCase() : '';
  if (src){
    return (
      <img src={src} alt={name||'Avatar'} style={{
        width:size, height:size, borderRadius:'50%',
        objectFit:'cover', objectPosition:'center',
        border: border ? `2px solid #fff` : 'none',
        flexShrink:0, display:'block',
        background: `linear-gradient(135deg, ${a?.[0]||'#A8C8A0'}, ${a?.[1]||'#5A9060'})`,
      }}/>
    );
  }
  return (
    <div style={{
      width:size, height:size, borderRadius:'50%',
      background:`linear-gradient(135deg, ${a?.[0]||'#A8C8A0'}, ${a?.[1]||'#5A9060'})`,
      display:'flex', alignItems:'center', justifyContent:'center',
      color:'#fff', fontWeight:700, fontSize:size*0.36,
      border: border ? `2px solid #fff` : 'none',
      flexShrink:0,
    }}>{initials}</div>
  );
}

function Badge({type, sm=false, label, color, bg}){
  const M = {
    deal:    {l:'Deal',     bg:T.amberL, c:T.amber},
    angebot: {l:'Angebot',  bg:T.greenL, c:T.green},
    sos:     {l:'Hilfe',    bg:T.careL,  c:T.care},
    gesuch:  {l:'Gesuch',   bg:T.purpleL,c:T.purple},
    frage:   {l:'Frage',    bg:T.tealL,  c:T.teal},
    event:   {l:'Event',    bg:T.goldL,  c:T.gold},
    service: {l:'Service',  bg:T.tealL,  c:T.teal},
  };
  const x = label && color ? {l:label, bg:bg||T.greenL, c:color} : (M[type]||M.angebot);
  return (
    <span style={{
      display:'inline-flex', alignItems:'center', gap:4,
      background:x.bg, color:x.c, fontWeight:700,
      fontSize: sm?10:11, padding: sm?'2px 7px':'3px 9px',
      borderRadius:6, letterSpacing:'.2px', whiteSpace:'nowrap',
    }}>{x.l}</span>
  );
}

function Pill({active, onClick, children, color}){
  return (
    <button onClick={onClick} className="cp" style={{
      padding:'7px 13px', borderRadius:10,
      border:`1px solid ${active?(color||T.text):T.bdr}`,
      background:active?(color||T.text):'#fff',
      color:active?'#fff':T.text,
      fontSize:12.5, fontWeight:700, cursor:'pointer',
      whiteSpace:'nowrap',
    }}>{children}</button>
  );
}

function Btn({onClick, children, kind='primary', size='md', icon, full, disabled, style:s={}}){
  const sizes = {sm:{p:'8px 14px',f:13}, md:{p:'12px 18px',f:14}, lg:{p:'15px 22px',f:15}};
  const sz = sizes[size];
  const kinds = {
    primary: {bg:T.text, c:'#fff', b:T.text},
    secondary: {bg:'#fff', c:T.text, b:T.bdr},
    ghost: {bg:'transparent', c:T.text, b:'transparent'},
    danger: {bg:T.red, c:'#fff', b:T.red},
    success: {bg:T.green, c:'#fff', b:T.green},
    care: {bg:T.care, c:'#fff', b:T.care},
  };
  const k = kinds[kind] || kinds.primary;
  return (
    <button onClick={onClick} disabled={disabled} className="cp" style={{
      padding:sz.p, fontSize:sz.f, fontWeight:700,
      borderRadius:11, border:`1px solid ${k.b}`,
      background:k.bg, color:k.c,
      cursor:disabled?'not-allowed':'pointer',
      opacity:disabled?0.5:1,
      width:full?'100%':'auto',
      display:'inline-flex', alignItems:'center', justifyContent:'center', gap:7,
      ...s,
    }}>
      {icon && <span style={{fontSize:sz.f+1}}>{icon}</span>}
      {children}
    </button>
  );
}

function Input({label, value, onChange, placeholder, type='text', max, hint, error, multiline, rows=3, prefix}){
  return (
    <label style={{display:'block', marginBottom:14}}>
      {label && <div style={{fontSize:12, fontWeight:700, color:T.sec, marginBottom:6, letterSpacing:'.2px'}}>{label}{max?<span style={{color:T.muted, fontWeight:500, marginLeft:6}}>· max {max}</span>:null}</div>}
      <div style={{position:'relative', display:'flex', alignItems:'center'}}>
        {prefix && <span style={{position:'absolute', left:13, color:T.muted, fontSize:14, fontWeight:600, pointerEvents:'none'}}>{prefix}</span>}
        {multiline
          ? <textarea value={value} onChange={e=>onChange(e.target.value)} placeholder={placeholder} rows={rows} maxLength={max}
              style={{width:'100%', padding:'11px 14px', borderRadius:11, border:`1.5px solid ${error?T.red:T.bdr}`, background:'#FAFAF7', fontSize:14, color:T.text, resize:'none', lineHeight:1.5, fontFamily:'inherit', outline:'none'}}/>
          : <input type={type} value={value} onChange={e=>onChange(e.target.value)} placeholder={placeholder} maxLength={max}
              style={{width:'100%', padding: prefix?'11px 14px 11px 32px':'11px 14px', borderRadius:11, border:`1.5px solid ${error?T.red:T.bdr}`, background:'#FAFAF7', fontSize:14, color:T.text, outline:'none'}}/>
        }
      </div>
      {hint && !error && <div style={{fontSize:11, color:T.muted, marginTop:5, fontWeight:500}}>{hint}</div>}
      {error && <div style={{fontSize:11, color:T.red, marginTop:5, fontWeight:600}}>{error}</div>}
    </label>
  );
}

function Toast({msg, onClose}){
  useEffect(()=>{
    if (!msg) return;
    const id = setTimeout(onClose, 2800);
    return ()=>clearTimeout(id);
  },[msg]);
  if (!msg) return null;
  return (
    <div className="aIn" style={{
      position:'fixed', bottom:120, left:'50%', transform:'translateX(-50%)',
      background:T.text, color:'#fff', padding:'12px 18px', borderRadius:12,
      fontSize:13, fontWeight:600, zIndex:100, boxShadow:'0 12px 32px rgba(0,0,0,.18)',
      maxWidth:'85%', textAlign:'center', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis',
    }}>{msg}</div>
  );
}

function Sheet({open, onClose, children, title, height='auto'}){
  if (!open) return null;
  return (
    <div onClick={onClose} style={{
      position:'fixed', inset:0, background:'rgba(0,0,0,.4)', zIndex:90,
      display:'flex', alignItems:'flex-end', justifyContent:'center',
    }}>
      <div onClick={e=>e.stopPropagation()} className="aSheet" style={{
        width:'100%', maxWidth:430, background:'#fff',
        borderRadius:'22px 22px 0 0', maxHeight:'90vh', height,
        overflowY:'auto', boxShadow:'0 -10px 40px rgba(0,0,0,.15)',
      }}>
        <div style={{display:'flex', justifyContent:'center', padding:'10px 0 4px'}}>
          <div style={{width:36, height:4, borderRadius:2, background:'#E0E0DD'}}/>
        </div>
        {title && <div style={{padding:'8px 22px 14px', fontSize:18, fontWeight:800, fontFamily:'Fraunces, serif', letterSpacing:'-.3px'}}>{title}</div>}
        {children}
      </div>
    </div>
  );
}

function Modal({open, onClose, children, title, maxWidth=380}){
  if (!open) return null;
  return (
    <div onClick={onClose} style={{
      position:'fixed', inset:0, background:'rgba(0,0,0,.5)', zIndex:95,
      display:'flex', alignItems:'center', justifyContent:'center', padding:18,
    }}>
      <div onClick={e=>e.stopPropagation()} className="aIn" style={{
        background:'#fff', borderRadius:18, padding:24, maxWidth, width:'100%',
        boxShadow:'0 20px 60px rgba(0,0,0,.25)',
      }}>
        {title && <div style={{fontSize:18, fontWeight:800, fontFamily:'Fraunces, serif', marginBottom:10, letterSpacing:'-.3px'}}>{title}</div>}
        {children}
      </div>
    </div>
  );
}

function StatusOverlay({status}){
  if (!status || status==='aktiv') return null;
  const M = {
    reserviert:{bg:'rgba(192,123,10,.9)', l:'RESERVIERT'},
    erledigt:{bg:'rgba(10,74,36,.9)', l:'ERLEDIGT'},
    'hilfe-gefunden':{bg:'rgba(10,74,36,.9)', l:'HILFE GEFUNDEN'},
    abgeholt:{bg:'rgba(10,74,36,.9)', l:'ABGEHOLT'},
    abgelaufen:{bg:'rgba(168,165,158,.95)', l:'ABGELAUFEN'},
  };
  const m = M[status]; if (!m) return null;
  return (
    <div style={{
      position:'absolute', inset:0, background:m.bg,
      display:'flex', alignItems:'center', justifyContent:'center',
      color:'#fff', fontWeight:800, fontSize:14, letterSpacing:'1.5px',
      borderRadius:'inherit', backdropFilter:'blur(2px)',
    }}>{m.l}</div>
  );
}

function TierBadge({tier}){
  const M = {
    verified:{l:'Verifiziert', c:T.care, bg:T.careL, i:'✓'},
    basic:{l:'BASIC', c:T.gold, bg:T.goldL, i:'✦'},
    pro:{l:'PRO', c:T.gold, bg:T.goldL, i:'✦'},
    premium:{l:'PREMIUM', c:T.gold, bg:T.goldL, i:'✦'},
  };
  if (!tier || tier==='buerger') return null;
  const m = M[tier]; if (!m) return null;
  return (
    <span style={{display:'inline-flex',alignItems:'center',gap:3, fontSize:9.5, fontWeight:800, color:m.c, background:m.bg, padding:'2px 6px', borderRadius:5, letterSpacing:'.4px'}}>
      <span>{m.i}</span><span>{m.l}</span>
    </span>
  );
}

function Empty({icon, title, sub, action}){
  return (
    <div style={{textAlign:'center', padding:'48px 24px'}}>
      <div style={{fontSize:42, marginBottom:10, opacity:.6}}>{icon}</div>
      <div style={{fontFamily:'Fraunces, serif', fontSize:20, fontWeight:700, letterSpacing:'-.3px', marginBottom:6}}>{title}</div>
      <div style={{fontSize:13, color:T.sec, lineHeight:1.55, marginBottom:18, fontWeight:500}}>{sub}</div>
      {action}
    </div>
  );
}

// ─── EXPORT ──────────────────────────────────────────────────────
Object.assign(window, {
  T, timeAgo, useCountdown, fmtPrice,
  Avatar, Badge, Pill, Btn, Input, Toast, Sheet, Modal, StatusOverlay, TierBadge, Empty,
});
