// Mobile Field App — iOS-frame mockup with tabbed screens

function PhoneFrame({ children, screen, setScreen }) {
  const SCREENS = ['dashboard','deal','visit','quick'];
  const LABELS = ['Dashboard','Deal','Site Visit','Quick Add'];

  return (
    <div style={{ display:'flex', flexDirection:'column', alignItems:'center', gap:20 }}>
      {/* Screen switcher */}
      <div style={{ display:'flex', gap:2, background:'var(--surface-2)', border:'1px solid var(--border)', borderRadius:8, padding:3 }}>
        {SCREENS.map((s,i) => (
          <button key={s} onClick={() => setScreen(s)}
            style={{ padding:'5px 14px', borderRadius:6, border:'none', fontSize:12, fontWeight:screen===s?600:400,
              background: screen===s ? 'var(--surface)' : 'transparent',
              color: screen===s ? 'var(--ink)' : 'var(--ink-3)',
              boxShadow: screen===s ? 'var(--shadow-sm)' : 'none', cursor:'pointer' }}>
            {LABELS[i]}
          </button>
        ))}
      </div>

      {/* Phone bezel */}
      <div style={{ width:320, background:'#1A1A1A', borderRadius:44, padding:'14px 10px', boxShadow:'0 32px 80px rgba(0,0,0,0.4), 0 0 0 1px rgba(255,255,255,0.07), inset 0 0 0 1px rgba(255,255,255,0.04)', position:'relative' }}>
        {/* Dynamic island */}
        <div style={{ width:80, height:28, background:'#1A1A1A', borderRadius:99, position:'absolute', top:14, left:'50%', transform:'translateX(-50%)', zIndex:10 }}></div>
        {/* Screen */}
        <div style={{ background:'white', borderRadius:34, overflow:'hidden', position:'relative', minHeight:580 }}>
          {/* Status bar */}
          <div style={{ height:44, background:'transparent', position:'absolute', top:0, left:0, right:0, zIndex:5, display:'flex', alignItems:'flex-end', padding:'0 24px 6px', justifyContent:'space-between' }}>
            <span style={{ fontSize:13, fontWeight:700, color:screen==='dashboard'?'white':'var(--ink)' }}>9:41</span>
            <div style={{ display:'flex', gap:5, alignItems:'center' }}>
              <span style={{ fontSize:11, color:screen==='dashboard'?'white':'var(--ink)' }}>●●●</span>
              <span style={{ fontSize:11, color:screen==='dashboard'?'white':'var(--ink)' }}>WiFi</span>
              <span style={{ fontSize:11, color:screen==='dashboard'?'white':'var(--ink)' }}>🔋</span>
            </div>
          </div>
          {children}
          {/* Home indicator */}
          <div style={{ height:24, display:'flex', alignItems:'center', justifyContent:'center', background:'white', paddingBottom:4 }}>
            <div style={{ width:100, height:4, background:'var(--ink)', borderRadius:99, opacity:0.15 }}></div>
          </div>
        </div>
      </div>
    </div>
  );
}

function MobileApp({ deals, contacts, reps, showToast }) {
  const toast = showToast || (() => {});
  const [screen, setScreen] = React.useState('dashboard');
  const [selectedDeal, setSelectedDeal] = React.useState(deals.filter(d=>d.stage!=='sold'&&d.stage!=='lost')[0]);
  const [checkItems, setCheckItems] = React.useState({
    ppe: false, electrical: false, plumbing: false, access: false, photo: false
  });
  const [quickNote, setQuickNote] = React.useState('');
  const [checkedIn, setCheckedIn] = React.useState(false);
  const [budget, setBudget] = React.useState('');
  const [leadName, setLeadName] = React.useState('');
  const AI_OK = window.claude && typeof window.claude.complete === 'function';
  const [aiSug, setAiSug] = React.useState('');
  React.useEffect(() => {
    let alive = true; setAiSug('');
    if (!AI_OK || !selectedDeal || screen !== 'deal') return;
    (async () => {
      try {
        const raw = await window.claude.complete({ messages: [{ role:'user', content:`In one short sentence, give the single next best action for this kitchen/cabinetry sales deal. Customer: ${selectedDeal.customer}; stage: ${selectedDeal.stage}; value: $${selectedDeal.value||0}; ${selectedDeal.lastActivityDaysAgo} days since last activity. Imperative, under 22 words, no preamble.` }] });
        if (alive && raw) setAiSug(String(raw).trim());
      } catch (e) {}
    })();
    return () => { alive = false; };
  }, [screen, selectedDeal && selectedDeal.id]);

  const myDeals = deals.filter(d=>d.stage!=='sold'&&d.stage!=='lost').slice(0,5);
  const todayTasks = [
    { time:'9:00am', type:'Site visit', name:'Sarah Thornton', addr:'14 Banksia St, Mosman' },
    { time:'11:30am', type:'Design appt', name:'Marcus Webb', addr:'Showroom — Bay' },
    { time:'2:00pm', type:'Follow-up call', name:'Priya Nair', addr:'Phone' },
  ];

  const fmtShort = v => '$' + Math.round((v||0)/1000) + 'k';

  return (
    <div style={{ display:'grid', gridTemplateColumns:'320px 1fr', gap:40, alignItems:'start' }}>
      <PhoneFrame screen={screen} setScreen={setScreen}>

        {/* ── SCREEN 1: Dashboard ── */}
        {screen === 'dashboard' && (
          <div style={{ minHeight:580 }}>
            {/* Hero gradient header */}
            <div style={{ background:'linear-gradient(160deg, var(--accent) 0%, #0A4F3C 100%)', padding:'52px 20px 20px', color:'white' }}>
              <div style={{ fontSize:12, opacity:0.75 }}>Good morning,</div>
              <div style={{ fontSize:20, fontWeight:700, letterSpacing:'-0.01em', marginBottom:12 }}>{(reps[0]||{name:'Alex'}).name.split(' ')[0]}</div>
              <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:8 }}>
                {[
                  { label:'My Active Deals', value: myDeals.length },
                  { label:'Stuck > 21d', value: myDeals.filter(d=>d.lastActivityDaysAgo>21).length },
                ].map(s => (
                  <div key={s.label} style={{ background:'rgba(255,255,255,0.12)', borderRadius:10, padding:'10px 12px' }}>
                    <div style={{ fontSize:10, opacity:0.75, textTransform:'uppercase', letterSpacing:'0.06em' }}>{s.label}</div>
                    <div style={{ fontSize:24, fontWeight:700, letterSpacing:'-0.02em' }}>{s.value}</div>
                  </div>
                ))}
              </div>
            </div>
            {/* Today's schedule */}
            <div style={{ padding:'14px 16px' }}>
              <div style={{ fontSize:12, fontWeight:700, color:'var(--ink)', textTransform:'uppercase', letterSpacing:'0.06em', marginBottom:10 }}>Today's Schedule</div>
              {todayTasks.map((t,i) => (
                <div key={i} style={{ display:'flex', gap:10, padding:'9px 0', borderBottom:'1px solid var(--border)', alignItems:'flex-start' }}>
                  <div style={{ fontSize:11, fontFamily:'var(--mono)', color:'var(--ink-3)', minWidth:48, marginTop:1 }}>{t.time}</div>
                  <div style={{ flex:1 }}>
                    <div style={{ fontSize:13, fontWeight:600, color:'var(--ink)' }}>{t.name}</div>
                    <div style={{ fontSize:11, color:'var(--ink-3)', marginTop:2 }}>{t.type} · {t.addr}</div>
                  </div>
                  <div style={{ width:8, height:8, borderRadius:99, background:['var(--accent)','var(--warn)','var(--info)'][i], marginTop:5, flexShrink:0 }}></div>
                </div>
              ))}
              {/* Quick actions */}
              <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:8, marginTop:14 }}>
                {[['📞','Log a call'],['📐','New site visit'],['💬','Send message'],['+ Deal','Quick add']].map(([icon,label]) => (
                  <button key={label} onClick={() => label==='New site visit'?setScreen('visit'):label==='Quick add'?setScreen('quick'):null}
                    style={{ padding:'10px 8px', background:'var(--surface-2)', border:'1px solid var(--border)', borderRadius:10, fontSize:12, fontWeight:500, color:'var(--ink-2)', cursor:'pointer', display:'flex', flexDirection:'column', alignItems:'center', gap:4 }}>
                    <span style={{ fontSize:18 }}>{icon}</span>{label}
                  </button>
                ))}
              </div>
            </div>
          </div>
        )}

        {/* ── SCREEN 2: Deal Detail ── */}
        {screen === 'deal' && selectedDeal && (
          <div style={{ minHeight:580 }}>
            <div style={{ background:'var(--surface-2)', padding:'48px 16px 12px', borderBottom:'1px solid var(--border)' }}>
              <div style={{ fontSize:11, color:'var(--ink-3)', marginBottom:2 }}>{selectedDeal.id}</div>
              <div style={{ fontSize:18, fontWeight:700, color:'var(--ink)', letterSpacing:'-0.01em' }}>{selectedDeal.customer}</div>
              <div style={{ display:'flex', gap:8, alignItems:'center', marginTop:6 }}>
                <span style={{ background: selectedDeal.stage==='in_progress'?'var(--s-in_progress)':'var(--s-possible)', color:'white', fontSize:10, fontWeight:700, borderRadius:99, padding:'2px 8px' }}>
                  {selectedDeal.stage==='in_progress'?'In Progress':'Possible'}
                </span>
                <span style={{ fontSize:12, fontFamily:'var(--mono)', color:'var(--ink-2)', fontWeight:600 }}>${(selectedDeal.value||0).toLocaleString()}</span>
              </div>
            </div>
            <div style={{ padding:'12px 16px', display:'flex', flexDirection:'column', gap:2 }}>
              {[
                { label:'Rep', value: selectedDeal.repName },
                { label:'Last activity', value: selectedDeal.lastActivityDaysAgo===0?'Today':`${selectedDeal.lastActivityDaysAgo}d ago` },
                { label:'Location', value: selectedDeal.suburb || '—' },
              ].map(row => (
                <div key={row.label} style={{ display:'flex', justifyContent:'space-between', padding:'8px 0', borderBottom:'1px solid var(--border)', fontSize:13 }}>
                  <span style={{ color:'var(--ink-3)' }}>{row.label}</span>
                  <span style={{ fontWeight:600, color:'var(--ink)' }}>{row.value}</span>
                </div>
              ))}
              {/* AI next action */}
              <div style={{ marginTop:10, padding:'10px 12px', background:'#F3EEFF', borderRadius:10, border:'1px solid #DDD6FE' }}>
                <div style={{ fontSize:11, fontWeight:700, color:'#5B21B6', marginBottom:4 }}>✦ AI Suggestion</div>
                <div style={{ fontSize:12, color:'#5B21B6', lineHeight:1.5 }}>{aiSug || "Quote hasn't been opened in 7 days. Send a brief follow-up to check if they have questions."}</div>
              </div>
              {/* Actions */}
              <div style={{ display:'flex', flexDirection:'column', gap:6, marginTop:8 }}>
                <button style={{ padding:'11px 14px', background:'var(--accent)', color:'white', border:'none', borderRadius:10, fontSize:13, fontWeight:600, cursor:'pointer' }} onClick={() => toast('Call logged for ' + (selectedDeal?.customer || 'deal'))}>📞 Log a call</button>
                <button style={{ padding:'11px 14px', background:'var(--surface-2)', border:'1px solid var(--border)', borderRadius:10, fontSize:13, fontWeight:500, cursor:'pointer', color:'var(--ink-2)' }} onClick={() => toast('Note added')}>📝 Add note</button>
                <button style={{ padding:'11px 14px', background:'var(--surface-2)', border:'1px solid var(--border)', borderRadius:10, fontSize:13, fontWeight:500, cursor:'pointer', color:'var(--ink-2)' }} onClick={()=>setScreen('visit')}>📐 Site visit checklist</button>
              </div>
            </div>
          </div>
        )}

        {/* ── SCREEN 3: Site Visit ── */}
        {screen === 'visit' && (
          <div style={{ minHeight:580 }}>
            <div style={{ background:'var(--surface-2)', padding:'48px 16px 12px', borderBottom:'1px solid var(--border)' }}>
              <div style={{ fontSize:11, color:'var(--ink-3)', marginBottom:2 }}>Site Visit</div>
              <div style={{ fontSize:17, fontWeight:700, color:'var(--ink)' }}>WHS Safety Checklist</div>
            </div>
            <div style={{ padding:'12px 16px' }}>
              {/* GPS check-in */}
              <button onClick={() => setCheckedIn(p=>!p)}
                style={{ width:'100%', padding:'11px 14px', background: checkedIn ? 'var(--won)' : 'var(--surface-2)', border: `1px solid ${checkedIn?'var(--won)':'var(--border)'}`, borderRadius:10, fontSize:13, fontWeight:600, cursor:'pointer', color: checkedIn ? 'white' : 'var(--ink-2)', marginBottom:14, display:'flex', alignItems:'center', justifyContent:'center', gap:8 }}>
                📍 {checkedIn ? 'Checked in · 14 Banksia St' : 'GPS Check-in'}
              </button>

              {/* Checklist */}
              {[
                { id:'ppe', label:'PPE worn on site', sub:'Hard hat, hi-vis, safety boots' },
                { id:'electrical', label:'Electrical hazards assessed', sub:'Switchboard location confirmed' },
                { id:'plumbing', label:'Plumbing access checked', sub:'Shut-off valves located' },
                { id:'access', label:'Safe access confirmed', sub:'Pathways clear, lifting equipment' },
                { id:'photo', label:'Site photos taken', sub:'Min. 4 photos of existing kitchen' },
              ].map(item => (
                <div key={item.id} onClick={()=>setCheckItems(p=>({...p,[item.id]:!p[item.id]}))}
                  style={{ display:'flex', alignItems:'center', gap:10, padding:'9px 0', borderBottom:'1px solid var(--border)', cursor:'pointer' }}>
                  <div style={{ width:22, height:22, borderRadius:5, border:`2px solid ${checkItems[item.id]?'var(--won)':'var(--border)'}`, background: checkItems[item.id]?'var(--won)':'transparent', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
                    {checkItems[item.id] && <span style={{ color:'white', fontSize:13, fontWeight:700 }}>✓</span>}
                  </div>
                  <div style={{ flex:1 }}>
                    <div style={{ fontSize:13, fontWeight:500, color:'var(--ink)' }}>{item.label}</div>
                    <div style={{ fontSize:11, color:'var(--ink-3)' }}>{item.sub}</div>
                  </div>
                </div>
              ))}
              <div style={{ marginTop:10, fontSize:12, color:'var(--ink-3)' }}>
                {Object.values(checkItems).filter(Boolean).length}/5 items complete
              </div>
              <button style={{ width:'100%', marginTop:10, padding:'11px 14px', background: Object.values(checkItems).every(Boolean)?'var(--accent)':'var(--surface-3)', color: Object.values(checkItems).every(Boolean)?'white':'var(--ink-3)', border:'none', borderRadius:10, fontSize:13, fontWeight:600, cursor: Object.values(checkItems).every(Boolean)?'pointer':'not-allowed' }}
                onClick={() => { if (Object.values(checkItems).every(Boolean)) toast('Checklist submitted · signature requested'); }}>
                {Object.values(checkItems).every(Boolean) ? '✓ Submit & get signature →' : 'Complete all items first'}
              </button>
            </div>
          </div>
        )}

        {/* ── SCREEN 4: Quick Add ── */}
        {screen === 'quick' && (
          <div style={{ minHeight:580 }}>
            <div style={{ background:'var(--surface-2)', padding:'48px 16px 12px', borderBottom:'1px solid var(--border)' }}>
              <div style={{ fontSize:17, fontWeight:700, color:'var(--ink)' }}>Quick Add</div>
              <div style={{ fontSize:12, color:'var(--ink-3)', marginTop:2 }}>Log it fast, fill in details later</div>
            </div>
            <div style={{ padding:'14px 16px', display:'flex', flexDirection:'column', gap:10 }}>
              <div>
                <label style={{ fontSize:11, fontWeight:600, textTransform:'uppercase', letterSpacing:'0.06em', color:'var(--ink-3)', display:'block', marginBottom:5 }}>Customer name</label>
                <input placeholder="e.g. Jane Smith" style={{ width:'100%', padding:'10px 12px', border:'1px solid var(--border)', borderRadius:9, fontSize:14, outline:'none', background:'var(--surface-2)', boxSizing:'border-box' }} />
              </div>
              <div>
                <label style={{ fontSize:11, fontWeight:600, textTransform:'uppercase', letterSpacing:'0.06em', color:'var(--ink-3)', display:'block', marginBottom:5 }}>Phone</label>
                <input type="tel" placeholder="+61 4XX XXX XXX" style={{ width:'100%', padding:'10px 12px', border:'1px solid var(--border)', borderRadius:9, fontSize:14, outline:'none', background:'var(--surface-2)', boxSizing:'border-box' }} />
              </div>
              <div>
                <label style={{ fontSize:11, fontWeight:600, textTransform:'uppercase', letterSpacing:'0.06em', color:'var(--ink-3)', display:'block', marginBottom:5 }}>Quick note</label>
                <textarea value={quickNote} onChange={e=>setQuickNote(e.target.value)} placeholder="What did you discuss? Budget, timeline, product interest…"
                  rows={3} style={{ width:'100%', padding:'10px 12px', border:'1px solid var(--border)', borderRadius:9, fontSize:13, outline:'none', background:'var(--surface-2)', resize:'none', fontFamily:'var(--font)', lineHeight:1.5, boxSizing:'border-box' }} />
              </div>
              <div>
                <label style={{ fontSize:11, fontWeight:600, textTransform:'uppercase', letterSpacing:'0.06em', color:'var(--ink-3)', display:'block', marginBottom:5 }}>Estimated budget</label>
                <div style={{ display:'flex', gap:6 }}>
                  {['<$20k','$20–50k','$50–100k','>$100k'].map(b => (
                    <button key={b} onClick={() => setBudget(b)} style={{ flex:1, padding:'7px 4px', background: budget===b ? 'var(--accent-soft)' : 'var(--surface-2)', border:'1px solid ' + (budget===b ? 'var(--accent)' : 'var(--border)'), borderRadius:7, fontSize:11, fontWeight:500, cursor:'pointer', color: budget===b ? 'var(--accent-ink)' : 'var(--ink-2)' }}>{b}</button>
                  ))}
                </div>
              </div>
              <button style={{ marginTop:4, padding:'13px 14px', background:'var(--accent)', color:'white', border:'none', borderRadius:11, fontSize:14, fontWeight:700, cursor:'pointer' }}
                onClick={() => { toast('Lead saved' + (budget ? ' · ' + budget : '')); setQuickNote(''); setBudget(''); setLeadName(''); }}>
                Save lead →
              </button>
              <button style={{ padding:'11px 14px', background:'var(--surface-2)', border:'1px solid var(--border)', borderRadius:11, fontSize:13, color:'var(--ink-3)', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center', gap:6 }}
                onClick={() => toast('🎙️ Recording… speak your note')}>
                🎙️ Voice note instead
              </button>
            </div>
          </div>
        )}
      </PhoneFrame>

      {/* Side notes */}
      <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
        <div style={{ fontSize:18, fontWeight:700, color:'var(--ink)', letterSpacing:'-0.02em' }}>Mobile Field App</div>
        <div style={{ fontSize:14, color:'var(--ink-3)', lineHeight:1.7 }}>
          A fully offline-capable PWA for sales designers in the field. GPS check-in, site visit checklists, quick lead capture, and real-time deal updates — all from a phone.
        </div>
        <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
          {[
            { icon:'📍', title:'GPS Check-in', desc:'Auto-log arrival at customer site with location stamp' },
            { icon:'✦', title:'AI Next Action', desc:'Instant suggestion for each deal based on activity history' },
            { icon:'📐', title:'Site Visit Checklist', desc:'Digital WHS checklist with photo capture and e-signature' },
            { icon:'🎙️', title:'Voice Notes', desc:'Dictate notes hands-free on site, transcribed automatically' },
            { icon:'📵', title:'Works Offline', desc:'Full functionality even in dead zones — syncs when back online' },
          ].map(f => (
            <div key={f.title} style={{ display:'flex', gap:12, padding:'11px 14px', background:'var(--surface)', border:'1px solid var(--border)', borderRadius:10 }}>
              <span style={{ fontSize:20, flexShrink:0 }}>{f.icon}</span>
              <div>
                <div style={{ fontSize:13, fontWeight:600, color:'var(--ink)' }}>{f.title}</div>
                <div style={{ fontSize:12, color:'var(--ink-3)', marginTop:2 }}>{f.desc}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

window.MobileApp = MobileApp;
