// Simple Pro Mobile — Standard/Premium feature surfaces + cohesive placeholders
const STANDARD_FEATURES = [
  'Belle calls, booking, and core workflow',
  'Invoicing, payments, and digital proposals/e-sign',
  'Google Calendar sync',
  'Automated follow-ups and Google Reviews',
  'Recurring jobs and maintenance plans',
];

const PREMIUM_FEATURES = [
  'Tech voice commands to Belle',
  'Live video/photo pre-screen and diagnosis',
  'Receipt scanning, job costs, and inventory',
  'Geo/location and arrival notifications',
  'Outbound Belle',
  'Advanced reporting and analytics',
  'Customer financing',
  'Custom branding',
  'Priority onboarding and support',
];

const FEATURE_META = {
  'voice-commands': { title:'Voice commands', premium:true, icon:'🎙️', sub:'Techs can talk to Belle hands-free from the field.', bullets:['Start driving, mark arrived, add notes, and report issues by voice.','Field-safe: no billing or owner-only actions exposed to technicians.','Owner controls live in Settings → Plans.'] },
  'live-diagnosis': { title:'Live photo/video diagnosis', premium:true, icon:'📹', sub:'Pre-screen jobs before dispatch and capture better scope.', bullets:['Customer photo/video intake before the visit.','Belle summarizes likely scope and flags parts needed.','Attach diagnosis notes to the job record.'] },
  'receipts-inventory': { title:'Receipts, job costs, inventory', premium:true, icon:'🧾', sub:'Scan receipts and track material costs against jobs.', bullets:['Receipt scan → vendor, total, tax, and line items.','Job costing summary for owners.','Inventory reminders for common truck stock.'] },
  'location-notifications': { title:'Location + arrival notifications', premium:true, icon:'📍', sub:'Keep customers updated automatically as techs move.', bullets:['Geo-based “on the way” and arrival updates.','Owner dispatch visibility without exposing revenue to techs.','Customer ETA messages stay under Belle control.'] },
  'outbound-belle': { title:'Outbound Belle', premium:true, icon:'☎️', sub:'Belle can proactively call leads and customers.', bullets:['Call missed leads, unscheduled estimates, and follow-up queues.','Owner approval controls and transcripts.','Never exposed as a technician billing action.'] },
  'reports': { title:'Advanced reporting', premium:true, icon:'📊', sub:'Owner analytics for work, money, and team throughput.', bullets:['Revenue, close rate, unpaid balance, and job completion trends.','Technician utilization and dispatch exceptions.','Export-ready summaries for weekly owner review.'] },
  'customer-financing': { title:'Customer financing', premium:true, icon:'💳', sub:'Offer financing on larger estimates and invoices.', bullets:['Financing CTA on eligible proposals.','Belle can explain options and collect customer intent.','Owner-visible status on billing records.'] },
  'custom-branding': { title:'Custom branding', premium:true, icon:'🎨', sub:'Match proposals, invoices, and customer messages to your brand.', bullets:['Logo, brand color, and message tone controls.','Branded PDFs and proposal pages.','Owner-only settings.'] },
  'priority-support': { title:'Priority onboarding/support', premium:true, icon:'⚡', sub:'Faster setup help for teams adopting Belle.', bullets:['Priority onboarding checklist.','Faster support lane.','Configuration review for calls, schedule, billing, and team roles.'] },
  'reviews': { title:'Google Reviews', premium:false, icon:'⭐', sub:'Standard follow-up engine for review requests.', bullets:['Belle asks happy customers at the right moment.','Track requests from the job timeline.','Owner controls templates and timing.'] },
  'recurring-jobs': { title:'Recurring jobs', premium:false, icon:'🔁', sub:'Maintenance plans and repeat visits are included in Standard.', bullets:['Create recurring schedules from a job.','Belle confirms upcoming visits.','Great for maintenance plans and inspections.'] },
  'proposals': { title:'Digital proposals + e-sign', premium:false, icon:'✍️', sub:'Send clean proposals customers can approve on mobile.', bullets:['Estimate → proposal → approval.','Digital signature capture.','Convert approved proposals into jobs or invoices.'] },
};

function isPremiumPlan(plan) {
  const p = String(plan || '').toLowerCase();
  return p === 'premium' || p === 'pro' || p.includes('premium') || p.includes('ops');
}
function featureMeta(key) { return FEATURE_META[key] || FEATURE_META.reviews; }

function FeatureDetailScreen({ onNav, params, plan='standard', role }) {
  const key = params?.feature || params?.key || 'reviews';
  const meta = featureMeta(key);
  const locked = meta.premium && !isPremiumPlan(plan);
  const isTech = role === 'technician';
  return (
    <div style={screenBg({paddingBottom:110})}>
      <NavHeader title={meta.title} onBack="__back"/>
      <div style={{padding:'16px'}}>
        <div style={{borderRadius:26,padding:18,background:locked?'rgba(255,255,255,0.72)':'linear-gradient(145deg,rgba(15,23,42,0.98),rgba(49,46,129,0.94))',color:locked?'#111827':'white',boxShadow:'0 14px 30px rgba(15,23,42,0.10)',border:'0.5px solid rgba(0,0,0,0.06)'}}>
          <div style={{display:'flex',alignItems:'center',gap:12}}>
            <div style={{width:44,height:44,borderRadius:16,background:locked?'#fef3c7':'rgba(255,255,255,0.15)',display:'flex',alignItems:'center',justifyContent:'center',fontSize:22}}>{locked?'🔒':meta.icon}</div>
            <div style={{flex:1}}>
              <div style={{fontSize:22,fontWeight:850,letterSpacing:'-0.045em'}}>{meta.title}</div>
              <div style={{fontSize:13,lineHeight:1.35,opacity:locked?0.62:0.72,marginTop:4}}>{locked?'Premium feature — upgrade to enable.':meta.sub}</div>
            </div>
          </div>
        </div>
        <div style={{marginTop:14,borderRadius:22,background:'rgba(255,255,255,0.86)',border:'0.5px solid rgba(0,0,0,0.06)',overflow:'hidden'}}>
          {meta.bullets.map((b,i)=>(
            <div key={b} style={{padding:'13px 15px',display:'flex',gap:10,borderBottom:i<meta.bullets.length-1?'0.5px solid rgba(0,0,0,0.06)':'none'}}>
              <div style={{width:22,height:22,borderRadius:'50%',background:locked?'#f3f4f6':'#eef6ff',color:locked?'#9ca3af':'#007aff',display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0}}>{locked?'•':Icons.check}</div>
              <div style={{fontSize:14,lineHeight:1.45,color:locked?'rgba(17,24,39,0.55)':'#111827'}}>{b}</div>
            </div>
          ))}
        </div>
        {isTech && meta.premium && (
          <div style={{marginTop:12,fontSize:12.5,lineHeight:1.45,color:'rgba(17,24,39,0.52)',padding:'0 3px'}}>Technician view only exposes field-safe controls. Owner billing, financing, reporting, and plan controls stay hidden.</div>
        )}
        <PrimaryButton label={locked?'View Premium plans':'Open workflow'} color={locked?'#0f172a':'#007aff'} onTap={()=>locked?onNav('plans'):onNav(meta.premium && isTech ? 'belle' : 'home')} style={{marginTop:16}}/>
      </div>
    </div>
  );
}

function ReportsScreen({ onNav, plan='standard' }) {
  const locked = !isPremiumPlan(plan);
  if (locked) return <FeatureDetailScreen onNav={onNav} params={{feature:'reports'}} plan={plan}/>;
  const stats = [
    ['Revenue',' $42.8k','+18%'],['Close rate','64%','+7 pts'],['Unpaid',' $3.1k','-12%'],['Utilization','82%','Healthy']
  ];
  return (
    <div style={screenBg({paddingBottom:110})}>
      <NavHeader title="Reports" onBack="__back"/>
      <div style={{padding:'16px'}}>
        <div style={{borderRadius:24,padding:16,background:'linear-gradient(145deg,#0f172a,#312e81)',color:'white',boxShadow:'0 14px 30px rgba(15,23,42,0.16)'}}>
          <div style={{fontSize:13,opacity:.65,fontWeight:700,letterSpacing:'.04em',textTransform:'uppercase'}}>Premium analytics</div>
          <div style={{fontSize:24,fontWeight:850,letterSpacing:'-.045em',marginTop:5}}>Belle found 3 owner exceptions</div>
          <div style={{fontSize:13,opacity:.7,lineHeight:1.35,marginTop:6}}>Unpaid invoices, under-booked Thursday, and one tech running hot on overtime.</div>
        </div>
        <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:10,marginTop:12}}>{stats.map(s=><div key={s[0]} style={{borderRadius:20,background:'rgba(255,255,255,.86)',border:'0.5px solid rgba(0,0,0,.06)',padding:14}}><div style={{fontSize:12,color:'rgba(17,24,39,.48)',fontWeight:700}}>{s[0]}</div><div style={{fontSize:24,fontWeight:850,letterSpacing:'-.05em',marginTop:8}}>{s[1]}</div><div style={{fontSize:12,color:'#1a9e5c',fontWeight:700,marginTop:3}}>{s[2]}</div></div>)}</div>
        <SectionHeader title="Belle recommendations"/>
        <Card mx={0}>{['Send reminders for 4 invoices','Move Friday overflow to Dani R.','Offer financing on Steinberg proposal'].map((x,i)=><ListCell key={x} title={x} subtitle="Owner review" icon={Icons.sparkle} onTap={()=>onNav(i===2?'customer-financing':'belle',{prompt:x})} isLast={i===2}/>)}</Card>
      </div>
    </div>
  );
}

function TechScheduleScreen({ onNav, params }) {
  const tech = params?.tech || 'Marcus L.';
  const rows = [
    {time:'8:00 AM', job:'Water Heater Install', client:'Chen Family', status:'completed'},
    {time:'11:30 AM', job:'Drain Clog — Kitchen', client:'Ramos Residence', status:'in progress'},
    {time:'2:00 PM', job:'Full Bathroom Re-pipe', client:'Steinberg Corp', status:'scheduled'},
  ];
  return (
    <div style={screenBg({paddingBottom:110})}>
      <NavHeader title={`${tech}'s day`} onBack="__back"/>
      <div style={{padding:'16px'}}>
        <div style={{borderRadius:24,padding:16,background:'rgba(255,255,255,.86)',border:'0.5px solid rgba(0,0,0,.06)',boxShadow:'0 10px 24px rgba(15,23,42,.06)'}}>
          <div style={{display:'flex',alignItems:'center',gap:12}}><Avatar name={tech} size={46}/><div><div style={{fontSize:20,fontWeight:850,letterSpacing:'-.04em'}}>{tech}</div><div style={{fontSize:13,color:'rgba(17,24,39,.5)',marginTop:2}}>3 jobs · 6.5h scheduled · Belle routing active</div></div></div>
        </div>
        <div style={{marginTop:12,borderRadius:22,background:'rgba(255,255,255,.86)',border:'0.5px solid rgba(0,0,0,.06)',overflow:'hidden'}}>{rows.map((r,i)=><div key={r.time} onClick={()=>onNav('job-detail',{job:(window.JOBS_DATA||[]).find(j=>j.client===r.client)})} style={{padding:'13px 15px',display:'flex',alignItems:'center',gap:12,borderBottom:i<rows.length-1?'0.5px solid rgba(0,0,0,.06)':'none',cursor:'pointer'}}><div style={{width:58,fontSize:12,fontWeight:800,color:'#007aff'}}>{r.time}</div><div style={{flex:1,minWidth:0}}><div style={{fontSize:14.5,fontWeight:760}}>{r.job}</div><div style={{fontSize:12.3,color:'rgba(17,24,39,.48)',marginTop:2}}>{r.client}</div></div><Badge status={r.status} small/></div>)}</div>
      </div>
    </div>
  );
}

Object.assign(window, { STANDARD_FEATURES, PREMIUM_FEATURES, FeatureDetailScreen, ReportsScreen, TechScheduleScreen, isPremiumPlan });

// ── PREMIUM OPERATIONAL ADDITIONS ─────────────────────────────
Object.assign(FEATURE_META, {
  approvals: { title:'Owner Approval Center', premium:true, icon:'✅', sub:'Belle queues decisions that need owner judgment.', bullets:['Pricing changes, discounts, financing offers, schedule exceptions, and scope changes.','Technicians can report issues; owners approve or reject.','Belle applies the decision and updates the customer/job timeline.'] },
  'job-costing': { title:'Job costing + margin', premium:true, icon:'📈', sub:'See profit per job from labor, parts, receipts, and invoice.', bullets:['Labor + parts + receipts + invoice total in one margin view.','Better than generic analytics because it is tied to each job.','Owner-only financial visibility.'] },
  handoff: { title:'Belle handoff summaries', premium:false, icon:'📝', sub:'Scope and customer context before and after the visit.', bullets:['Before arrival: scope, tone, photos, assumptions, risks.','After completion: customer summary, invoice/payment status, follow-up plan.','Technicians see field-safe context; owners see financial follow-up.'] },
  'escalation-rules': { title:'Escalation rules', premium:true, icon:'🚨', sub:'Tell Belle exactly when to notify the owner.', bullets:['Price changes above threshold, VIP callers, tech late, financing requests.','Route alerts to owner approval center.','Keep urgent exceptions visible without interrupting normal jobs.'] },
});

function LockedShell({ onNav, feature, children, plan }) {
  const locked = !((typeof isPremiumPlan === 'function') ? isPremiumPlan(plan) : ((typeof isPremiumPlan === 'function') ? isPremiumPlan(plan) : String(plan||'').toLowerCase().includes('premium')));
  if (!locked) return children;
  return <FeatureDetailScreen onNav={onNav} params={{feature}} plan={plan}/>;
}

function ApprovalsScreen({ onNav, plan='standard' }) {
  const rows = [
    {type:'Scope change', job:'Drain Clog — Ramos', ask:'Add camera inspection +$180', by:'Marcus L.', tag:'Tech reported'},
    {type:'Financing offer', job:'Full Bath Re-pipe', ask:'Offer 12-month financing', by:'Belle', tag:'Customer asked'},
    {type:'Discount', job:'Nguyen Group', ask:'Approve $75 goodwill discount', by:'Belle', tag:'Late arrival'},
    {type:'Schedule exception', job:'Steinberg Corp', ask:'Move Jake into overtime window', by:'Dispatcher', tag:'Owner approval'},
  ];
  return <LockedShell onNav={onNav} feature="approvals" plan={plan}>
    <div style={screenBg({paddingBottom:110})}>
      <NavHeader title="Approvals" onBack="__back"/>
      <div style={{padding:'16px'}}>
        <div style={{borderRadius:24,padding:16,background:'linear-gradient(145deg,#0f172a,#312e81)',color:'white',boxShadow:'0 14px 30px rgba(15,23,42,.16)'}}>
          <div style={{fontSize:13,fontWeight:800,letterSpacing:'.05em',textTransform:'uppercase',opacity:.68}}>Belle owner queue</div>
          <div style={{fontSize:26,fontWeight:850,letterSpacing:'-.05em',marginTop:5}}>4 decisions waiting</div>
          <div style={{fontSize:13,lineHeight:1.35,opacity:.72,marginTop:5}}>Pricing, financing, discounts, scope, and schedule exceptions stay under owner control.</div>
        </div>
        <div style={{marginTop:12,borderRadius:22,background:'rgba(255,255,255,.86)',border:'0.5px solid rgba(0,0,0,.06)',overflow:'hidden'}}>{rows.map((r,i)=><div key={r.ask} onClick={()=>onNav('belle',{prompt:`Approve or reject: ${r.ask}`})} style={{padding:'14px 15px',borderBottom:i<rows.length-1?'0.5px solid rgba(0,0,0,.06)':'none',cursor:'pointer'}}><div style={{display:'flex',justifyContent:'space-between',gap:8}}><div style={{fontSize:12,fontWeight:800,color:'#007aff',textTransform:'uppercase',letterSpacing:'.04em'}}>{r.type}</div><Badge status="attention" small/></div><div style={{fontSize:16,fontWeight:800,letterSpacing:'-.025em',marginTop:5}}>{r.ask}</div><div style={{fontSize:12.5,color:'rgba(17,24,39,.5)',marginTop:4}}>{r.job} · {r.by} · {r.tag}</div></div>)}</div>
      </div>
    </div>
  </LockedShell>;
}

function JobCostingScreen({ onNav, params, plan='standard' }) {
  const job = params?.job || (window.JOBS_DATA || [])[0] || {name:'Drain Clog — Kitchen', client:'Ramos Residence', amount:'$320'};
  const rows = [['Invoice', job.amount || '$320', '#1a9e5c'],['Labor', '-$96', '#dc2626'],['Parts', '-$42', '#dc2626'],['Receipts', '-$18', '#dc2626'],['Margin', '$164 · 51%', '#007aff']];
  return <LockedShell onNav={onNav} feature="job-costing" plan={plan}>
    <div style={screenBg({paddingBottom:110})}>
      <NavHeader title="Job Costing" onBack="__back"/>
      <div style={{padding:'16px'}}>
        <div style={{borderRadius:24,padding:16,background:'rgba(255,255,255,.88)',border:'0.5px solid rgba(0,0,0,.06)',boxShadow:'0 10px 24px rgba(15,23,42,.06)'}}><div style={{fontSize:13,color:'rgba(17,24,39,.48)',fontWeight:700}}>Current job</div><div style={{fontSize:22,fontWeight:850,letterSpacing:'-.045em',marginTop:4}}>{job.name}</div><div style={{fontSize:13,color:'rgba(17,24,39,.52)',marginTop:3}}>{job.client}</div></div>
        <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:10,marginTop:12}}><div style={{borderRadius:20,background:'#e6f7ef',padding:14}}><div style={{fontSize:12,color:'#0f6b3c',fontWeight:800}}>Profit</div><div style={{fontSize:28,fontWeight:900,color:'#0f6b3c',letterSpacing:'-.06em',marginTop:8}}>$164</div></div><div style={{borderRadius:20,background:'#eef6ff',padding:14}}><div style={{fontSize:12,color:'#1e40af',fontWeight:800}}>Margin</div><div style={{fontSize:28,fontWeight:900,color:'#1e40af',letterSpacing:'-.06em',marginTop:8}}>51%</div></div></div>
        <SectionHeader title="Cost ledger"/>
        <Card mx={0}>{rows.map((r,i)=><div key={r[0]} style={{padding:'13px 16px',display:'flex',justifyContent:'space-between',borderBottom:i<rows.length-1?'0.5px solid rgba(0,0,0,.06)':'none'}}><div style={{fontSize:15,fontWeight:700}}>{r[0]}</div><div style={{fontSize:15,fontWeight:850,color:r[2]}}>{r[1]}</div></div>)}</Card>
        <PrimaryButton label="Open receipts + parts" onTap={()=>onNav('inventory',{job})} style={{marginTop:16}}/>
      </div>
    </div>
  </LockedShell>;
}

function HandoffScreen({ onNav, params, role }) {
  const job = params?.job || (window.JOBS_DATA || [])[0] || {name:'Drain Clog — Kitchen', client:'Ramos Residence'};
  const before = ['Kitchen drain backs up after dishwasher cycle','Customer is anxious but friendly; wants clear ETA','Photo shows cleanout under sink, no visible leak','Risk: may need camera inspection if cable does not clear'];
  const after = ['Cleared main kitchen line and tested flow','Invoice ready; payment link sent by Belle','Ask for Google Review after payment clears','Owner follow-up if camera add-on is declined'];
  return <div style={screenBg({paddingBottom:110})}>
    <NavHeader title="Belle Handoff" onBack="__back"/>
    <div style={{padding:'16px'}}>
      <div style={{borderRadius:24,padding:16,background:'linear-gradient(145deg,#0f172a,#312e81)',color:'white'}}><div style={{fontSize:22,fontWeight:850,letterSpacing:'-.045em'}}>{job.name}</div><div style={{fontSize:13,opacity:.7,marginTop:4}}>{job.client} · field-safe summary</div></div>
      {[['Before arrival',before],['After completion',after]].map((group,gi)=><div key={group[0]}><SectionHeader title={group[0]}/><Card mx={0}>{group[1].map((b,i)=><ListCell key={b} icon={gi?Icons.check:Icons.sparkle} iconBg={gi?'#e6f7ef':'#f5f0ff'} title={b} subtitle={role==='technician'?'Field context':'Owner + Belle context'} chevron={false} isLast={i===group[1].length-1}/>)}</Card></div>)}
    </div>
  </div>;
}

function EscalationRulesScreen({ onNav, plan='standard' }) {
  const rules = [['Price change threshold','Over $150'],['VIP caller','Notify owner immediately'],['Tech running late','15 minutes past ETA'],['Financing request','Queue owner approval'],['Scope change from tech','Always require approval']];
  return <LockedShell onNav={onNav} feature="escalation-rules" plan={plan}>
    <div style={screenBg({paddingBottom:110})}><NavHeader title="Escalation Rules" onBack="__back"/><SectionHeader title="Notify owner when"/><Card>{rules.map((r,i)=><ListCell key={r[0]} icon={Icons.warning} iconBg="#fef3e2" title={r[0]} subtitle={r[1]} onTap={()=>onNav('approvals')} isLast={i===rules.length-1}/>)}</Card></div>
  </LockedShell>;
}

function InventoryScreen({ onNav, params, plan='standard', role }) {
  const locked = role !== 'technician' && !((typeof isPremiumPlan === 'function') ? isPremiumPlan(plan) : ((typeof isPremiumPlan === 'function') ? isPremiumPlan(plan) : String(plan||'').toLowerCase().includes('premium')));
  if (locked) return <FeatureDetailScreen onNav={onNav} params={{feature:'receipts-inventory'}} plan={plan} role={role}/>;
  const parts = [['1.5” P-trap','Used today','Truck stock: 2'],['Drain cable head','Used today','Reorder soon'],['PVC primer/cement','Common material','Truck stock: OK']];
  return <div style={screenBg({paddingBottom:110})}><NavHeader title="Parts + Inventory" onBack="__back"/><div style={{padding:'16px'}}><div style={{borderRadius:24,padding:16,background:'rgba(255,255,255,.88)',border:'0.5px solid rgba(0,0,0,.06)'}}><div style={{fontSize:22,fontWeight:850,letterSpacing:'-.045em'}}>{role==='technician'?'Parts used':'Job materials'}</div><div style={{fontSize:13,color:'rgba(17,24,39,.52)',lineHeight:1.4,marginTop:4}}>{role==='technician'?'Add safe material notes for owner review.':'Receipts, job costs, and light reorder reminders — not warehouse software.'}</div></div><SectionHeader title="Materials"/><Card mx={0}>{parts.map((p,i)=><ListCell key={p[0]} icon={Icons.camera} iconBg="#eef6ff" title={p[0]} subtitle={`${p[1]} · ${p[2]}`} onTap={()=>role==='technician'?onNav('belle',{prompt:`Add ${p[0]} to parts used`}):onNav('job-costing')} isLast={i===parts.length-1}/>)}</Card>{role!=='technician'&&<PrimaryButton label="Scan receipt" onTap={()=>onNav('feature-detail',{feature:'receipts-inventory'})} style={{marginTop:16}}/>}</div></div>;
}

Object.assign(window, { ApprovalsScreen, JobCostingScreen, HandoffScreen, EscalationRulesScreen, InventoryScreen });
