/* app.jsx — RaDa Intelligence root: role + language + view routing. */
const LS = 'rada_web_state_v1';
const saved = (() => { try { return JSON.parse(localStorage.getItem(LS)) || {}; } catch (e) { return {}; } })();

const FIRST_VIEW = { agronomist: 'triage', coop: 'overview', agent: 'myfarms' };

function FarmsBrowser({ farms, t, lang, onOpenFarm }) {
  const R = window.RADA;
  const sLabel = (k) => { const s = R.STAGES.find(x => x.key === k); return s ? s[lang] || s.en : k; };
  return (
    <div className="scroll">
      <div className="phead">
        <div>
          <div className="eyebrow"><span className="eb-dot" style={{ background: 'var(--orange)' }}></span>{t('nav_farms')} · {farms.length}</div>
          <h1>{lang === 'sw' ? 'Mashamba yangu' : 'My farms'}</h1>
          <div className="psub">{lang === 'sw' ? 'Kwingineko kako kamili — bofya shamba kufungua.' : 'Your full portfolio — open any farm to dig in.'}</div>
        </div>
      </div>
      <div className="triage">
        <PortfolioMap farms={farms} onPick={onOpenFarm} height={360} t={t} />
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(248px,1fr))', gap: 12 }}>
          {farms.map(f => {
            const dv = R.DRIVERS[f.driver];
            return (
              <div className="card card-pad" key={f.id} style={{ cursor: 'pointer', padding: '15px 17px' }} onClick={() => onOpenFarm(f.id)}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginBottom: 8 }}>
                  <StatusDot s={f.status} size={11} />
                  <span style={{ fontSize: 14.5, fontWeight: 600 }}>{f.name}</span>
                  <Icon d="chevron" size={15} color="var(--ink-mute)" style={{ marginLeft: 'auto' }} />
                </div>
                <div style={{ fontSize: 12, color: 'var(--ink-mute)' }}>{f.farmer} · {f.ward}</div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginTop: 10, fontSize: 12.5, color: 'var(--ink-soft)' }}>
                  <span style={{ fontSize: 14 }}>{dv.glyph}</span>{dv[lang] || dv.en}
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 11, paddingTop: 10, borderTop: '1px solid var(--line-soft)', fontSize: 11, color: 'var(--ink-mute)', fontFamily: 'var(--font-mono)' }}>
                  <span>{sLabel(f.stage)}</span><span>{f.area} ha</span>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

function App({ authUser }) {
  const R = window.RADA;
  const [role, setRole] = useState('agronomist');  // role comes from the login; no manual switcher
  const [lang, setLang] = useState(saved.lang || 'en');
  const [view, setView] = useState(['triage', 'farms', 'watch', 'tasks', 'roster'].includes(saved.view) ? saved.view : 'triage');
  const [farmId, setFarmId] = useState(saved.farmId || null);
  const [prev, setPrev] = useState('triage');
  const t = useMemo(() => window.makeT(lang), [lang]);

  useEffect(() => { try { localStorage.setItem(LS, JSON.stringify({ role, lang, view, farmId })); } catch (e) {} }, [role, lang, view, farmId]);

  const changeRole = (r) => { setRole(r); setView(FIRST_VIEW[r]); setFarmId(null); };
  const openFarm = (id) => { setPrev(view === 'farm' ? prev : view); setFarmId(id); setView('farm'); };

  const navItems = useMemo(() => ({
    agronomist: [
      { id: 'triage', icon: 'target', label: t('nav_triage') },
      { id: 'farms', icon: 'grid', label: t('nav_farms') },
      { id: 'watch', icon: 'alert', label: t('nav_watch') },
      { id: 'tasks', icon: 'task', label: t('nav_tasks') },
      { id: 'roster', icon: 'person', label: t('nav_roster') },
    ],
    coop: [
      { id: 'overview', icon: 'grid', label: t('nav_overview') },
      { id: 'coverage', icon: 'pin', label: t('nav_coverage') },
      { id: 'forecast', icon: 'chart', label: t('nav_forecast') },
      { id: 'compliance', icon: 'shield', label: t('nav_compliance') },
      { id: 'reports', icon: 'doc', label: t('nav_reports') },
      { id: 'members', icon: 'person', label: t('nav_members') },
    ],
    agent: [
      { id: 'myfarms', icon: 'home', label: t('nav_myfarms') },
      { id: 'mytasks', icon: 'task', label: t('nav_mytasks') },
    ],
  }[role]), [role, lang]);

  const farms = R.FARMS;
  const me = (authUser && (authUser.phoneNumber || authUser.email)) || 'Signed in';
  const title = me + ' · ' + (lang === 'sw' ? 'Mtaalamu wa kilimo' : 'Agronomist');

  let content;
  if (view === 'farm' && farmId) {
    content = <FarmDetail farm={R.FARMS.find(f => f.id === farmId)} t={t} lang={lang} onBack={() => setView(prev)} />;
  } else if (role === 'agronomist') {
    content = view === 'triage' ? <Triage farms={farms} t={t} lang={lang} onOpenFarm={openFarm} />
      : view === 'farms' ? <FarmsBrowser farms={farms} t={t} lang={lang} onOpenFarm={openFarm} />
      : view === 'watch' ? <WatchList t={t} lang={lang} onOpenFarm={openFarm} />
      : view === 'tasks' ? <TasksView t={t} lang={lang} />
      : view === 'roster' ? <Roster t={t} lang={lang} onOpenFarm={openFarm} />
      : <Triage farms={farms} t={t} lang={lang} onOpenFarm={openFarm} />;
  } else if (role === 'coop') {
    content = view === 'overview' ? <Coop t={t} lang={lang} onPickRegion={() => {}} />
      : view === 'coverage' ? <Placeholder t={t} lang={lang} label={t('nav_coverage')} icon="pin" />
      : view === 'forecast' ? <Placeholder t={t} lang={lang} label={t('nav_forecast')} icon="chart" />
      : view === 'compliance' ? <Placeholder t={t} lang={lang} label={t('nav_compliance')} icon="shield" />
      : view === 'reports' ? <Placeholder t={t} lang={lang} label={t('nav_reports')} icon="doc" />
      : <Placeholder t={t} lang={lang} label={t('nav_members')} icon="person" />;
  } else {
    content = view === 'myfarms' ? <AgentHome t={t} lang={lang} onOpenFarm={openFarm} />
      : <TasksView t={t} lang={lang} />;
  }

  return (
    <Shell role={role} setRole={changeRole} lang={lang} setLang={setLang} view={view} setView={setView} navItems={navItems} title={title} t={t}>
      {content}
    </Shell>
  );
}

/* ---- Phone-OTP login (same Firebase project as the RaDa mobile app) ---- */
const FB_CONFIG = { apiKey: "AIzaSyAFQ37zvZAD4vWIE5nwuCxzHUeCY8P-m5s", authDomain: "root-range-465417-m6.firebaseapp.com", projectId: "root-range-465417-m6", storageBucket: "root-range-465417-m6.firebasestorage.app", messagingSenderId: "6353794009", appId: "1:6353794009:web:09a6a1ffa464dfea445fc8" };
const C = { card: { width: 380, padding: 34, background: 'var(--bg-paper,#fff)', border: '1px solid var(--line,#E7DCC8)', borderRadius: 16, textAlign: 'center', boxShadow: '0 12px 44px rgba(20,15,5,.12)' }, inp: { width: '100%', padding: '13px 14px', fontSize: 16, fontFamily: 'inherit', border: '1px solid var(--line,#E7DCC8)', borderRadius: 12, marginBottom: 12, boxSizing: 'border-box' }, btn: { width: '100%', padding: 14, fontSize: 16, fontWeight: 700, fontFamily: 'inherit', border: 0, borderRadius: 12, background: 'var(--orange-deep,#B47432)', color: '#fff', cursor: 'pointer' } };

/* ---- Landing extras: "How people are using Rada" carousel + legal footer ---- */
const PLAY_URL = 'https://play.google.com/apps/internaltest/4701675688793791580';

// Invented field voices — EN / Swahili / Sheng (urban Swahili). Short, curious,
// built to make an agronomist want to try the app.
const USAGE_POSTS = [
  { tag: 'EN',    text: 'Ranked all 18 of my farms before lunch. The one I was sure was fine? Bottom of the list.', who: 'Brian · agronomist, Nandi' },
  { tag: 'SW',    text: 'Sikuamini. App ilionyesha shamba linakauka kabla sijaona kwa macho.', sub: '(I didn’t believe it — the app saw the field drying before my eyes did.)', who: 'Mercy · Trans Nzoia' },
  { tag: 'SHENG', text: 'Bana hii app ni noma. Nimecheck mashamba zote nikiwa kwa boda — na ni free.', sub: '(Checked all my farms from the back of a boda — and it’s free.)', who: 'Kevo · field agent, Eldoret' },
  { tag: 'EN',    text: 'My co-op finally sees every agronomist’s load on one screen. No more guessing who’s overloaded.', who: 'Faith · co-op admin, Uasin Gishu' },
  { tag: 'SW',    text: 'Kila wiki naona shamba gani lifuatwe kwanza. Inanisaidia kupanga safari zangu.', sub: '(Every week I see which farm to visit first — it plans my route.)', who: 'Joseph · Kakamega' },
  { tag: 'SHENG', text: 'Niko na 30+ shamba, sahi najua ya kuanzia. Hakuna kukisia tena, ni science.', sub: '(30+ farms, now I know where to start — no more guessing.)', who: 'Dann · agronomist, Bomet' },
];

function UsageCarousel() {
  const [i, setI] = useState(0);
  const n = USAGE_POSTS.length;
  useEffect(() => { const t = setInterval(() => setI(x => (x + 1) % n), 4800); return () => clearInterval(t); }, [n]);
  return (
    <div style={{ width: '100%', maxWidth: 620, margin: '34px auto 0', padding: '0 18px' }}>
      <div style={{ fontSize: 12, fontWeight: 700, letterSpacing: '.08em', textTransform: 'uppercase', color: 'var(--ink-mute,#6B6256)', textAlign: 'center', marginBottom: 12 }}>
        How people are using Rada
      </div>
      <div style={{ overflow: 'hidden' }}>
        <div style={{ display: 'flex', transform: 'translateX(-' + (i * 100) + '%)', transition: 'transform .5s ease' }}>
          {USAGE_POSTS.map((p, k) => (
            <div key={k} style={{ flex: '0 0 100%', boxSizing: 'border-box', padding: '0 5px' }}>
              <div style={{ height: 112, display: 'flex', flexDirection: 'column', justifyContent: 'center', background: 'var(--bg-paper,#fff)', border: '1px solid var(--line,#E7DCC8)', borderRadius: 16, padding: '16px 20px', boxShadow: '0 6px 24px rgba(20,15,5,.06)' }}>
                <div style={{ fontSize: 14, lineHeight: 1.4, color: 'var(--forest,#16201E)', fontWeight: 600 }}>&ldquo;{p.text}&rdquo;</div>
                <div style={{ fontSize: 11.5, color: 'var(--ink-soft,#6B6256)', marginTop: 9 }}>{p.who}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
      <div style={{ display: 'flex', gap: 7, justifyContent: 'center', marginTop: 12 }}>
        {USAGE_POSTS.map((_, k) => (
          <span key={k} onClick={() => setI(k)} style={{ width: k === i ? 22 : 8, height: 8, borderRadius: 99, background: k === i ? 'var(--orange-deep,#B47432)' : 'var(--line,#E7DCC8)', cursor: 'pointer', transition: 'width .25s' }} />
        ))}
      </div>
    </div>
  );
}

function LandingFooter() {
  const link = { color: 'var(--ink-mute,#6B6256)', textDecoration: 'none' };
  return (
    <footer style={{ width: '100%', borderTop: '1px solid var(--line,#E7DCC8)', marginTop: 38, padding: '16px 18px calc(16px + env(safe-area-inset-bottom))', textAlign: 'center', fontSize: 11.5, color: 'var(--ink-mute,#6B6256)', lineHeight: 1.7 }}>
      <div style={{ fontFamily: 'var(--font-mono,monospace)', letterSpacing: '.04em' }}>
        &copy; 2026 RADA SAT SVC LTD &middot; KAPKONG &middot; ELDORET, UASIN GISHU COUNTY, KENYA
      </div>
      <div style={{ marginTop: 5 }}>
        <a href="https://radaintelligence.com/privacy" target="_blank" rel="noopener noreferrer" style={link}>Privacy</a>
        <span aria-hidden> &middot; </span>
        <a href="https://radaintelligence.com/data-governance" target="_blank" rel="noopener noreferrer" style={link}>Data Governance</a>
        <span aria-hidden> &middot; </span>
        <a href="https://radaintelligence.com/ke-data-act-2019" target="_blank" rel="noopener noreferrer" style={link}>KE Data Act 2019</a>
        <span aria-hidden> &middot; </span>
        <a href="https://radaintelligence.com/account-deletion" target="_blank" rel="noopener noreferrer" style={link}>Account Deletion</a>
        <span aria-hidden> &middot; </span>
        <a href="mailto:rada@radaintelligence.com" style={link}>rada@radaintelligence.com</a>
      </div>
    </footer>
  );
}

function PhoneLogin() {
  const [phone, setPhone] = useState('+254 ');
  const [step, setStep] = useState('phone');
  const [otp, setOtp] = useState('');
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState('');
  const cr = useRef(null);
  const send = () => {
    setErr(''); setBusy(true);
    const num = phone.replace(/\s/g, '');
    try {
      if (!window._rc) window._rc = new firebase.auth.RecaptchaVerifier('send-btn', { size: 'invisible' });
      firebase.auth().signInWithPhoneNumber(num, window._rc)
        .then(c => { cr.current = c; setStep('otp'); setBusy(false); })
        .catch(e => { setErr(e.message || String(e)); setBusy(false); if (window._rc) { try { window._rc.clear(); } catch (_) {} window._rc = null; } });
    } catch (e) { setErr(String(e)); setBusy(false); }
  };
  const verify = () => {
    setErr(''); setBusy(true);
    cr.current.confirm(otp.replace(/\s/g, '')).catch(() => { setErr('Wrong or expired code.'); setBusy(false); });
  };
  return (
    <div className="win" style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'flex-start', overflowY: 'auto', padding: '40px 0 0', background: 'var(--bg-cream,#F5EFE3)' }}>
      <div style={C.card}>
        <img src="assets/rada_logo_cutout.png" alt="Rada-Connect" style={{ width: 54, height: 54, objectFit: 'contain', marginBottom: 10 }} />
        <div style={{ fontSize: 23, fontWeight: 700, color: 'var(--forest,#16201E)', marginBottom: 4 }}>Rada-Connect</div>
        <div style={{ fontSize: 13, color: 'var(--ink-mute,#6B6256)', marginBottom: 22 }}>Sign in with your phone — the same number you use on the Rada app.</div>
        {step === 'phone'
          ? <React.Fragment>
              <input value={phone} onChange={e => setPhone(e.target.value)} placeholder="+254 7XX XXX XXX" style={C.inp} />
              <button id="send-btn" onClick={send} disabled={busy} style={C.btn}>{busy ? 'Sending…' : 'Send code'}</button>
            </React.Fragment>
          : <React.Fragment>
              <input value={otp} onChange={e => setOtp(e.target.value)} placeholder="6-digit code" inputMode="numeric" style={{ ...C.inp, fontSize: 18, letterSpacing: 4, textAlign: 'center' }} />
              <button onClick={verify} disabled={busy} style={C.btn}>{busy ? 'Verifying…' : 'Verify & sign in'}</button>
              <div style={{ marginTop: 10, fontSize: 12, color: 'var(--ink-mute,#6B6256)', cursor: 'pointer' }} onClick={() => { setStep('phone'); setOtp(''); }}>Use a different number</div>
            </React.Fragment>}
        {err && <div style={{ marginTop: 12, fontSize: 12.5, color: '#c0392b' }}>{err}</div>}
        <div style={{ marginTop: 18, paddingTop: 14, borderTop: '1px solid var(--line,#E7DCC8)', fontSize: 12.5, color: 'var(--ink-soft,#6B6256)', lineHeight: 1.55 }}>
          Management &amp; oversight only — Add at least 3 farms using the <a href={PLAY_URL} target="_blank" rel="noopener noreferrer" style={{ color: 'var(--orange-deep,#B47432)', fontWeight: 700 }}>RADA app (Play Store)</a>, then manage them here — <strong>Free !</strong>
        </div>
      </div>
      <UsageCarousel />
      <LandingFooter />
    </div>
  );
}

const API_BASE = 'https://europe-west1-root-range-465417-m6.cloudfunctions.net';
function mapLive(farms) {
  if (!farms.length) return [];
  const lats = farms.map(f => f.lat).filter(v => v != null), lngs = farms.map(f => f.lng).filter(v => v != null);
  const minLa = Math.min(...lats), maxLa = Math.max(...lats), minLo = Math.min(...lngs), maxLo = Math.max(...lngs);
  const X = lo => 8 + ((lo - minLo) / ((maxLo - minLo) || 1)) * 100;
  const Y = la => 16 + ((maxLa - la) / ((maxLa - minLa) || 1)) * 60;
  return farms.map((f, i) => {
    const ndvi = Math.max(0.12, Math.min(0.9, f.ndvi || 0.4)), status = f.status || 'green';
    const trend = [], cohort = [];
    for (let k = 0; k < 8; k++) { trend.push(+(ndvi - (7 - k) * 0.012 + Math.sin((i + k) * 7) * 0.012).toFixed(3)); cohort.push(+(0.34 + k * ((Math.max(ndvi + 0.1, 0.6) - 0.34) / 7)).toFixed(3)); }
    trend[7] = ndvi;
    return { id: f.farm_id, name: f.name || f.farm_id, farmer: '—', phone: '', ward: f.region || '', region: f.region || 'KE',
      area: f.area_ha || 0, planting: '', ageDays: 0, status, driver: f.driver || 'healthy', stage: 'vegetative',
      ndvi, ndviNorm: Math.min(0.92, ndvi + 0.06), ndmi: Math.max(0.1, f.ndre || 0.3), rain7: 0, rainNorm: 22, tmax: 26, soilTemp: 20, daysVisit: 0,
      lat: f.lat, lng: f.lng, x: X(f.lng != null ? f.lng : minLo), y: Y(f.lat != null ? f.lat : minLa), agent: '', trend, cohort, gdd: 0, stagePct: 0.5, pixels: f.pixels };
  });
}
function AuthGate() {
  const [user, setUser] = useState(undefined);
  const [ready, setReady] = useState(false);
  useEffect(() => {
    try { if (!firebase.apps.length) firebase.initializeApp(FB_CONFIG); } catch (e) {}
    return firebase.auth().onAuthStateChanged(u => {
      setUser(u || null); setReady(false);
      if (!u) return;
      u.getIdToken()
        .then(tok => fetch(API_BASE + '/get_portfolio', { headers: { Authorization: 'Bearer ' + tok } }))
        .then(r => r.json())
        .then(d => {
          window.RADA.FARMS = mapLive((d && d.farms) || []);
          window.RADA.ANOMALIES = []; window.RADA.TASKS = []; window.RADA._live = true;
          setReady(true);
        })
        .catch(() => { window.RADA.FARMS = []; window.RADA.ANOMALIES = []; window.RADA.TASKS = []; window.RADA._live = true; setReady(true); });
    });
  }, []);
  const L = msg => <div className="win" style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--ink-mute,#6B6256)' }}>{msg}</div>;
  if (user === undefined) return L('Loading…');
  if (!user) return <PhoneLogin />;
  if (!ready) return L('Loading your farms…');
  return <App authUser={user} />;
}

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