// MobileApp — V1.12.2 (Janik 2026-04-26).
// Mobile basic-Layout. NICHT für Auth-Flow (Login/Register) — User muss
// bereits eingeloggt sein und Leadscraper aktiv nutzen.
//
// Bewusst eingegrenzt:
//   - 4 Bottom-Nav-Tabs: Home, Leads, Profil, Mehr
//   - Read-mostly: Schedule + Wizard sind Desktop-only (mobile zeigt
//     Hinweis "auf Desktop wechseln zum Bearbeiten")
//   - Hero-Card mit Gradient (aus Design-Bundle MScreenHome-Pattern)
//   - Bottom-Nav iOS-Style (44px-tall fixed)
//
// Mount: app.jsx checkt useIsMobile() → wenn mobile + authed → render <MobileApp/>
// Sonst Desktop-Layout wie bisher.

const MOBILE_BREAKPOINT = 768;

function useIsMobile() {
  const [isMobile, setIsMobile] = React.useState(
    typeof window !== 'undefined' ? window.innerWidth < MOBILE_BREAKPOINT : false,
  );
  React.useEffect(() => {
    if (typeof window === 'undefined') return;
    const handler = () => setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
    window.addEventListener('resize', handler);
    return () => window.removeEventListener('resize', handler);
  }, []);
  return isMobile;
}

// Mobile color tokens (aus Design-Bundle src/mobile-screens.jsx)
const MINK = '#0B0F19';
const MINK_MUTED = '#6B7280';
const MINK_SOFT = '#94A3B8';
const MBRAND = '#3465E3';
const MSURFACE = '#F4F7FD';
const MBORDER = '#E6ECF5';

function MobileApp({ profiles = [], profileId, setProfileId, feedbackByProfile = {}, onTab: _onTabIgnored, toast }) {
  const [tab, setTab] = React.useState('home');
  const activeProfile = profiles.find((p) => p.id === profileId) || profiles[0] || null;

  return (
    <div style={{ minHeight: '100vh', background: MSURFACE, paddingBottom: 64, fontFamily: '-apple-system, BlinkMacSystemFont, system-ui, sans-serif' }}>
      <MobileTopBar profile={activeProfile}/>
      {tab === 'home' && <MobileHome profile={activeProfile} profiles={profiles} onSwitchProfile={setProfileId} feedbackByProfile={feedbackByProfile}/>}
      {tab === 'leads' && <MobileLeads profile={activeProfile}/>}
      {tab === 'profile' && <MobileProfile profile={activeProfile} feedbackByProfile={feedbackByProfile}/>}
      {tab === 'more' && <MobileMore/>}
      <MobileBottomNav active={tab} onChange={setTab}/>
    </div>
  );
}

function MobileTopBar({ profile }) {
  const initial = profile?.initial || (profile?.name?.[0] ?? 'L');
  return (
    <div style={{
      height: 48, padding: '0 16px', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      background: '#fff', borderBottom: `1px solid ${MBORDER}`, position: 'sticky', top: 0, zIndex: 50,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <img src="./logo-blue.svg" alt="Leadscraper" style={{ height: 22, width: 'auto' }}/>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <span style={{ fontSize: 10, color: MINK_SOFT, padding: '2px 8px', borderRadius: 999, background: MSURFACE, border: `1px solid ${MBORDER}` }}>
          v{window.CortexAPI?.CLIENT_CORTEX_VERSION || '—'}
        </span>
        <div style={{
          width: 30, height: 30, borderRadius: 15, background: MBRAND, color: '#fff',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 12, fontWeight: 600,
        }}>{initial}</div>
      </div>
    </div>
  );
}

function MobileHome({ profile, profiles, onSwitchProfile, feedbackByProfile }) {
  if (!profile) {
    return (
      <div style={{ padding: '40px 20px', textAlign: 'center' }}>
        <div style={{ fontSize: 14, color: MINK_MUTED, marginBottom: 8 }}>Noch kein Profil angelegt.</div>
        <div style={{ fontSize: 12, color: MINK_SOFT }}>
          Lege dein erstes Profil auf einem Desktop an — der Wizard ist mobil noch nicht verfügbar.
        </div>
      </div>
    );
  }

  const fb = feedbackByProfile[profile.id] || {};
  const accepted = Object.values(fb).filter((v) => v === 'accepted').length;
  const rejected = Object.values(fb).filter((v) => v === 'rejected').length;
  const total = profile.leads?.length || 0;
  const newLeads = (profile.leads || []).filter((l) => !fb[l.id]).slice(0, 3);
  const matchPct = (accepted + rejected) > 0 ? Math.round((accepted / (accepted + rejected)) * 100) : 0;

  return (
    <div style={{ padding: '12px 16px 20px' }}>
      {/* Hero — heute für dich */}
      <div style={{
        padding: 18, borderRadius: 14, color: '#fff', marginBottom: 16,
        background: 'linear-gradient(135deg, #1479FC 0%, #6B5ED6 100%)',
      }}>
        <div style={{ fontSize: 11, opacity: 0.85, fontWeight: 500, letterSpacing: 0.4, textTransform: 'uppercase' }}>
          Heute für dich
        </div>
        <div style={{ fontSize: 28, fontWeight: 700, marginTop: 6, letterSpacing: -0.4 }}>
          {newLeads.length} neue Lead{newLeads.length === 1 ? '' : 's'}
        </div>
        <div style={{ fontSize: 13, opacity: 0.9, marginTop: 4 }}>
          {profile.name}
        </div>
      </div>

      {/* Quick-Stats */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8, marginBottom: 20 }}>
        <MStatCard label="Match-Rate" value={`${matchPct}%`}/>
        <MStatCard label="Bewertet" value={accepted + rejected}/>
        <MStatCard label="Leads gesamt" value={total}/>
      </div>

      {/* Aktives Profil + Switch */}
      {profiles.length > 1 && (
        <div style={{ marginBottom: 20 }}>
          <div style={{ fontSize: 11, color: MINK_SOFT, fontWeight: 500, textTransform: 'uppercase', letterSpacing: 0.4, marginBottom: 8 }}>
            Profile wechseln
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {profiles.map((p) => (
              <button
                key={p.id}
                type="button"
                onClick={() => onSwitchProfile?.(p.id)}
                style={{
                  padding: 12, borderRadius: 10, background: '#fff', border: `1px solid ${MBORDER}`,
                  display: 'flex', alignItems: 'center', gap: 10, textAlign: 'left',
                  outline: p.id === profile.id ? `2px solid ${MBRAND}` : 'none',
                }}
              >
                <div style={{
                  width: 32, height: 32, borderRadius: 8,
                  background: p.id === profile.id ? MBRAND : '#EEF2FE',
                  color: p.id === profile.id ? '#fff' : MBRAND,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 13, fontWeight: 600,
                }}>{p.initial}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 500, color: MINK, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                    {p.name}
                  </div>
                  <div style={{ fontSize: 11, color: MINK_MUTED }}>
                    {(p.leads || []).length} Leads
                  </div>
                </div>
              </button>
            ))}
          </div>
        </div>
      )}

      {/* Frische Leads */}
      {newLeads.length > 0 && (
        <div>
          <div style={{ fontSize: 11, color: MINK_SOFT, fontWeight: 500, textTransform: 'uppercase', letterSpacing: 0.4, marginBottom: 8 }}>
            Unbewertete Leads
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {newLeads.map((lead) => (
              <MobileLeadCard key={lead.id} lead={lead}/>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

function MStatCard({ label, value }) {
  return (
    <div style={{ padding: 12, borderRadius: 10, background: '#fff', border: `1px solid ${MBORDER}` }}>
      <div style={{ fontSize: 18, fontWeight: 700, color: MINK, letterSpacing: -0.3 }}>{value}</div>
      <div style={{ fontSize: 10, color: MINK_SOFT, marginTop: 2, fontWeight: 500 }}>{label}</div>
    </div>
  );
}

function MobileLeadCard({ lead }) {
  const initial = (lead.company || '?').charAt(0).toUpperCase();
  return (
    <div style={{ padding: 12, borderRadius: 10, background: '#fff', border: `1px solid ${MBORDER}`, display: 'flex', alignItems: 'center', gap: 10 }}>
      <div style={{
        width: 36, height: 36, borderRadius: 8, background: '#EEF2FE',
        color: MBRAND, fontSize: 13, fontWeight: 600,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>{initial}</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13, fontWeight: 500, color: MINK, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
          {lead.company}
        </div>
        <div style={{ fontSize: 11, color: MINK_MUTED }}>
          {lead.location || lead.city || '—'}
        </div>
      </div>
    </div>
  );
}

function MobileLeads({ profile }) {
  if (!profile) {
    return <div style={{ padding: 40, textAlign: 'center', color: MINK_MUTED, fontSize: 13 }}>Kein Profil ausgewählt.</div>;
  }
  const leads = profile.leads || [];
  return (
    <div style={{ padding: '12px 16px 20px' }}>
      <div style={{ fontSize: 18, fontWeight: 700, color: MINK, marginBottom: 12 }}>
        Leads <span style={{ fontSize: 13, color: MINK_SOFT, fontWeight: 500 }}>({leads.length})</span>
      </div>
      {leads.length === 0 ? (
        <div style={{ padding: '40px 20px', textAlign: 'center', background: '#fff', borderRadius: 12, border: `1px solid ${MBORDER}` }}>
          <div style={{ fontSize: 13, color: MINK_MUTED, marginBottom: 4 }}>Noch keine Leads.</div>
          <div style={{ fontSize: 11, color: MINK_SOFT }}>Starte einen Suchlauf auf dem Desktop.</div>
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {leads.map((lead) => <MobileLeadCard key={lead.id} lead={lead}/>)}
        </div>
      )}
    </div>
  );
}

function MobileProfile({ profile, feedbackByProfile }) {
  if (!profile) {
    return <div style={{ padding: 40, textAlign: 'center', color: MINK_MUTED, fontSize: 13 }}>Kein Profil.</div>;
  }
  const fb = feedbackByProfile[profile.id] || {};
  const accepted = Object.values(fb).filter((v) => v === 'accepted').length;
  const rejected = Object.values(fb).filter((v) => v === 'rejected').length;
  const total = (profile.leadQueries || []).length;

  return (
    <div style={{ padding: '12px 16px 20px' }}>
      <div style={{ fontSize: 22, fontWeight: 700, color: MINK, letterSpacing: -0.3, marginBottom: 4 }}>
        {profile.name}
      </div>
      <div style={{ fontSize: 13, color: MINK_MUTED, marginBottom: 16 }}>
        {profile.query}
      </div>

      <div style={{ padding: 14, borderRadius: 10, background: '#fff', border: `1px solid ${MBORDER}`, marginBottom: 12 }}>
        <div style={{ fontSize: 11, color: MINK_SOFT, fontWeight: 500, textTransform: 'uppercase', letterSpacing: 0.4, marginBottom: 8 }}>
          Bewertungs-Stand
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12 }}>
          <MStatCard label="Passt" value={accepted}/>
          <MStatCard label="Passt nicht" value={rejected}/>
          <MStatCard label="Suchläufe" value={total}/>
        </div>
      </div>

      <div style={{ padding: 14, borderRadius: 10, background: '#FFF7E6', border: `1px solid #FCD34D` }}>
        <div style={{ fontSize: 12, color: '#92400E', lineHeight: 1.5 }}>
          <strong>Mobil-Hinweis:</strong> Bewertungen, Zeitpläne und neue Profile bearbeitest du auf Desktop. Hier kannst du nur lesen.
        </div>
      </div>
    </div>
  );
}

function MobileMore() {
  return (
    <div style={{ padding: '12px 16px 20px' }}>
      <div style={{ fontSize: 18, fontWeight: 700, color: MINK, marginBottom: 12 }}>Mehr</div>
      <div style={{ background: '#fff', borderRadius: 10, border: `1px solid ${MBORDER}`, overflow: 'hidden' }}>
        <a href="/" style={{ display: 'block', padding: 14, fontSize: 14, color: MINK, borderBottom: `1px solid ${MBORDER}`, textDecoration: 'none' }}>
          → Auf Desktop wechseln
        </a>
        <a href="https://leadscraper.bot/help" target="_blank" rel="noreferrer" style={{ display: 'block', padding: 14, fontSize: 14, color: MINK, textDecoration: 'none' }}>
          Hilfe & Kontakt
        </a>
      </div>
      <div style={{ marginTop: 24, textAlign: 'center', fontSize: 11, color: MINK_SOFT }}>
        Cortex v{window.CortexAPI?.CLIENT_CORTEX_VERSION || '—'}
      </div>
    </div>
  );
}

function MobileBottomNav({ active, onChange }) {
  const tabs = [
    { id: 'home',    label: 'Home',     icon: '🏠' },
    { id: 'leads',   label: 'Leads',    icon: '👥' },
    { id: 'profile', label: 'Profil',   icon: '⊕' },
    { id: 'more',    label: 'Mehr',     icon: '⋯' },
  ];
  return (
    <div style={{
      position: 'fixed', bottom: 0, left: 0, right: 0,
      height: 64, background: '#fff', borderTop: `1px solid ${MBORDER}`,
      display: 'flex', justifyContent: 'space-around', alignItems: 'stretch',
      paddingBottom: 'env(safe-area-inset-bottom)', zIndex: 50,
    }}>
      {tabs.map((t) => (
        <button
          key={t.id}
          type="button"
          onClick={() => onChange?.(t.id)}
          style={{
            flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 2,
            background: 'transparent', border: 'none', padding: '8px 4px',
            color: active === t.id ? MBRAND : MINK_SOFT,
            fontWeight: active === t.id ? 600 : 500,
          }}
        >
          <span style={{ fontSize: 18, lineHeight: 1 }}>{t.icon}</span>
          <span style={{ fontSize: 10 }}>{t.label}</span>
        </button>
      ))}
    </div>
  );
}

Object.assign(window, { MobileApp, useIsMobile });
