// Simple Pro Mobile — Schedule Screen
const { useState } = React;

const WEEK_DAYS = [
  { day:'Sun', date:20, today:false },
  { day:'Mon', date:21, today:true  },
  { day:'Tue', date:22, today:false },
  { day:'Wed', date:23, today:false },
  { day:'Thu', date:24, today:false },
  { day:'Fri', date:25, today:false },
  { day:'Sat', date:26, today:false },
];

const SCHEDULE_BY_DAY = {
  21: [
    { id:1, time:'8:00',  end:'10:00', label:'Water Heater Install', client:'Chen Family',    status:'completed',   tech:'Marcus L.', color:'#e6f7ef', border:'#1a9e5c' },
    { id:2, time:'11:30', end:'13:00', label:'Drain Clog — Kitchen', client:'Ramos Residence',status:'in progress', tech:'Marcus L.', color:'#eff6ff', border:'#2563eb' },
    { id:3, time:'14:00', end:'17:00', label:'Full Bath Re-pipe',    client:'Steinberg Corp', status:'scheduled',   tech:'Jake T.',   color:'#f3f4f6', border:'#9ca3af' },
    { id:4, time:'17:30', end:'18:30', label:'Leak Inspection',      client:'Nguyen Group',   status:'scheduled',   tech:'Dani R.',   color:'#f3f4f6', border:'#9ca3af' },
  ],
  22: [
    { id:5, time:'9:00',  end:'10:30', label:'Backflow Preventer Test', client:'Park Residence', status:'scheduled', tech:'Dani R.', color:'#f3f4f6', border:'#9ca3af' },
    { id:6, time:'13:00', end:'15:00', label:'Gas Line Repair',         client:'Torres LLC',     status:'scheduled', tech:'Jake T.', color:'#fef3e2', border:'#d97706' },
  ],
  23: [
    { id:7, time:'10:00', end:'12:00', label:'Toilet Replacement',   client:'Adams Home',     status:'scheduled', tech:'Marcus L.', color:'#f3f4f6', border:'#9ca3af' },
  ],
  24: [],
  25: [
    { id:8, time:'9:00',  end:'11:00', label:'Sump Pump Install',    client:'Lewis Property', status:'scheduled', tech:'Marcus L.', color:'#f3f4f6', border:'#9ca3af' },
    { id:9, time:'14:00', end:'16:00', label:'Pipe Insulation',      client:'Hall Residence', status:'scheduled', tech:'Dani R.',   color:'#f3f4f6', border:'#9ca3af' },
  ],
};

const HOURS = [7,8,9,10,11,12,13,14,15,16,17,18];
const HOUR_H = 72; // px per hour

function timeToFrac(timeStr) {
  const [h, m] = timeStr.split(':').map(Number);
  return (h - 7) + (m / 60);
}

function ScheduleScreen({ onNav }) {
  const [selectedDay, setSelectedDay] = useState(21);
  const [viewMode, setViewMode] = useState('day'); // day | list
  const jobs = SCHEDULE_BY_DAY[selectedDay] || [];

  return (
    <div style={{background:'#f7f7f8', minHeight:'100%', paddingBottom:100, display:'flex', flexDirection:'column'}}>
      <NavHeader title="Schedule"
        action={
          <div style={{display:'flex',gap:4}}>
            {['day','list','route'].map(m => (
              <div key={m} onClick={() => setViewMode(m)}
                style={{height:30,padding:'0 12px',borderRadius:8,
                  background: viewMode===m ? '#0071e3' : 'rgba(255,255,255,0.12)',
                  color: viewMode===m ? 'white' : 'rgba(255,255,255,0.6)',
                  fontSize:13,fontWeight:500,display:'flex',alignItems:'center',cursor:'pointer'}}>
                {m==='day' ? 'Day' : m==='list' ? 'List' : 'Route'}
              </div>
            ))}
          </div>
        }
      />

      {/* Week strip — dark */}
      <div style={{background:'#0f172a',paddingBottom:14}}>
        <div style={{fontSize:15,fontWeight:600,color:'white',padding:'10px 20px 8px',letterSpacing:'-0.01em'}}>April 2026</div>
        <div style={{display:'flex',gap:0,padding:'0 12px'}}>
          {WEEK_DAYS.map(d => {
            const isSelected = d.date === selectedDay;
            const hasJobs = (SCHEDULE_BY_DAY[d.date] || []).length > 0;
            return (
              <div key={d.date} onClick={() => setSelectedDay(d.date)}
                style={{flex:1,display:'flex',flexDirection:'column',alignItems:'center',
                  gap:4,padding:'6px 2px',cursor:'pointer'}}>
                <span style={{fontSize:11,fontWeight:500,
                  color: isSelected ? '#60a5fa' : d.today ? 'rgba(255,255,255,0.9)' : 'rgba(255,255,255,0.35)',
                  letterSpacing:'0.005em'}}>{d.day}</span>
                <div style={{
                  width:34,height:34,borderRadius:'50%',
                  background: isSelected ? '#0071e3' : d.today ? 'rgba(255,255,255,0.1)' : 'transparent',
                  display:'flex',alignItems:'center',justifyContent:'center',
                  border: d.today && !isSelected ? '1.5px solid rgba(255,255,255,0.3)' : 'none',
                }}>
                  <span style={{fontSize:15,fontWeight: d.today || isSelected ? 700 : 400,
                    color: isSelected ? 'white' : d.today ? 'white' : 'rgba(255,255,255,0.7)'}}>{d.date}</span>
                </div>
                {hasJobs && <div style={{width:5,height:5,borderRadius:'50%',
                  background: isSelected ? '#60a5fa' : 'rgba(255,255,255,0.3)'}}/>}
              </div>
            );
          })}
        </div>
      </div>

      {viewMode === 'route' ? (
        /* ROUTE VIEW — optimized map with job stops */
        <div style={{flex:1,overflowY:'auto',padding:'14px 16px',paddingBottom:20}}>
          {/* Simulated route map */}
          <div style={{borderRadius:14,overflow:'hidden',border:'1px solid rgba(0,0,0,0.07)',
            height:200,background:'linear-gradient(135deg,#e8eef5 0%,#dde8f5 100%)',
            position:'relative',marginBottom:14}}>
            <svg width="100%" height="200" viewBox="0 0 358 200" style={{position:'absolute',inset:0}}>
              <rect width="358" height="200" fill="#e8eef5"/>
              <line x1="0" y1="100" x2="358" y2="100" stroke="#d0dae5" strokeWidth="14"/>
              <line x1="179" y1="0" x2="179" y2="200" stroke="#d0dae5" strokeWidth="8"/>
              <line x1="0" y1="50" x2="358" y2="150" stroke="#dce5f0" strokeWidth="6"/>
              {/* Route line */}
              <polyline points="40,160 100,80 200,120 280,50 320,90"
                stroke="#0071e3" strokeWidth="3" fill="none" strokeDasharray="6,3"/>
              {/* Stop markers */}
              {[[40,160,'1'],[100,80,'2'],[200,120,'3'],[280,50,'4']].map(([x,y,n]) => (
                <g key={n}>
                  <circle cx={x} cy={y} r="12" fill="#0071e3"/>
                  <text x={x} y={y+5} textAnchor="middle" fill="white" fontSize="11" fontWeight="700">{n}</text>
                </g>
              ))}
              <circle cx="320" cy="90" r="8" fill="white" stroke="#0071e3" strokeWidth="2"/>
              <text x="320" y="94" textAnchor="middle" fill="#0071e3" fontSize="9" fontWeight="600">HQ</text>
            </svg>
            <div style={{position:'absolute',top:10,right:10,background:'white',
              borderRadius:8,padding:'5px 10px',fontSize:11,fontWeight:600,color:'#0071e3',
              boxShadow:'0 1px 4px rgba(0,0,0,0.12)'}}>
              Optimized · 28.4 mi
            </div>
          </div>

          {/* Route stops */}
          {jobs.length === 0 ? (
            <div style={{textAlign:'center',color:'rgba(0,0,0,0.3)',padding:'40px 0',fontSize:14}}>No jobs scheduled</div>
          ) : (
            <Card>
              {jobs.map((j,i) => (
                <div key={j.id} onClick={() => onNav('job-detail',{})}
                  style={{padding:'12px 16px',display:'flex',alignItems:'center',gap:12,
                    borderBottom: i<jobs.length-1?'0.5px solid rgba(0,0,0,0.06)':'none',cursor:'pointer'}}>
                  <div style={{width:28,height:28,borderRadius:'50%',background:'#0071e3',
                    display:'flex',alignItems:'center',justifyContent:'center',
                    fontSize:12,fontWeight:700,color:'white',flexShrink:0}}>{i+1}</div>
                  <div style={{flex:1,minWidth:0}}>
                    <div style={{fontSize:14,fontWeight:500,color:'#111',marginBottom:2,
                      whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{j.label}</div>
                    <div style={{fontSize:12,color:'rgba(0,0,0,0.4)'}}>{j.client} · {j.time}</div>
                  </div>
                  <div style={{display:'flex',flexDirection:'column',alignItems:'flex-end',gap:3}}>
                    <Badge status={j.status} small/>
                    <div onClick={e=>{e.stopPropagation();}}
                      style={{fontSize:11,color:'#0071e3',fontWeight:500,cursor:'pointer'}}>
                      Directions →
                    </div>
                  </div>
                </div>
              ))}
            </Card>
          )}
        </div>
      ) : viewMode === 'list' ? (
        /* LIST VIEW */
        <div style={{flex:1,overflowY:'auto',paddingBottom:20}}>
          {jobs.length === 0 ? (
            <div style={{display:'flex',flexDirection:'column',alignItems:'center',padding:'60px 20px',
              color:'rgba(0,0,0,0.3)',gap:12}}>
              <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
              <div style={{fontSize:15,fontWeight:500}}>No jobs scheduled</div>
              <div style={{fontSize:13,color:'rgba(0,0,0,0.25)',textAlign:'center'}}>Tap + to add a job for this day</div>
            </div>
          ) : (
            <Card style={{marginTop:14}}>
              {jobs.map((j, i) => (
                <div key={j.id} onClick={() => onNav('job-detail', {job: JOBS_DATA ? JOBS_DATA[0] : j})}
                  style={{padding:'14px 16px',display:'flex',alignItems:'center',gap:12,
                    borderBottom: i<jobs.length-1 ? '0.5px solid rgba(0,0,0,0.07)':'none',cursor:'pointer'}}>
                  <div style={{width:4,alignSelf:'stretch',borderRadius:2,background:j.border,flexShrink:0}}/>
                  <div style={{flex:1,minWidth:0}}>
                    <div style={{fontSize:15,fontWeight:500,color:'#111',letterSpacing:'-0.008em',marginBottom:3}}>{j.label}</div>
                    <div style={{fontSize:12,color:'rgba(0,0,0,0.45)'}}>{j.client} · {j.time}–{j.end}</div>
                  </div>
                  <div style={{display:'flex',flexDirection:'column',alignItems:'flex-end',gap:4}}>
                    <Badge status={j.status} small/>
                    <span style={{fontSize:11,color:'rgba(0,0,0,0.35)',fontWeight:500}}>{j.tech}</span>
                  </div>
                </div>
              ))}
            </Card>
          )}
        </div>
      ) : (
        /* TIMELINE VIEW */
        <div style={{flex:1,overflowY:'auto',position:'relative'}}>
          <div style={{position:'relative',minHeight:HOURS.length * HOUR_H + 40}}>
            {/* Hour lines */}
            {HOURS.map(h => (
              <div key={h} style={{position:'absolute',left:0,right:0,top:(h-7)*HOUR_H,
                display:'flex',alignItems:'center',gap:0}}>
                <div style={{width:52,textAlign:'right',paddingRight:10,fontSize:11,
                  fontWeight:500,color:'rgba(0,0,0,0.3)',flexShrink:0,lineHeight:'1'}}>
                  {h === 12 ? '12 PM' : h < 12 ? `${h} AM` : `${h-12} PM`}
                </div>
                <div style={{flex:1,height:'0.5px',background:'rgba(0,0,0,0.08)'}}/>
              </div>
            ))}

            {/* Current time indicator */}
            {selectedDay === 21 && (
              <div style={{position:'absolute',left:52,right:0,top:4.5*HOUR_H+20,
                display:'flex',alignItems:'center',zIndex:10,pointerEvents:'none'}}>
                <div style={{width:10,height:10,borderRadius:'50%',background:'#dc2626',flexShrink:0,marginLeft:-5}}/>
                <div style={{flex:1,height:1.5,background:'#dc2626'}}/>
              </div>
            )}

            {/* Job blocks */}
            {jobs.map(j => {
              const top = timeToFrac(j.time) * HOUR_H;
              const height = (timeToFrac(j.end) - timeToFrac(j.time)) * HOUR_H - 4;
              return (
                <div key={j.id} onClick={() => onNav('job-detail', {})}
                  style={{
                    position:'absolute',
                    left:60,right:12,
                    top: top + 4,
                    height: Math.max(height, 44),
                    background: j.color,
                    borderRadius:10,
                    borderLeft:`3px solid ${j.border}`,
                    padding:'8px 10px',
                    cursor:'pointer',
                    overflow:'hidden',
                  }}>
                  <div style={{fontSize:13,fontWeight:600,color:'#111',letterSpacing:'-0.008em',
                    whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{j.label}</div>
                  <div style={{fontSize:11,color:'rgba(0,0,0,0.5)',marginTop:2}}>{j.client} · {j.tech}</div>
                </div>
              );
            })}

            {jobs.length === 0 && (
              <div style={{position:'absolute',left:60,right:12,top:120,
                border:'1.5px dashed rgba(0,0,0,0.12)',borderRadius:12,padding:'20px',
                display:'flex',flexDirection:'column',alignItems:'center',gap:6,cursor:'pointer'}}
                onClick={() => onNav('new-job')}>
                <div style={{color:'rgba(0,0,0,0.2)',fontSize:24}}>+</div>
                <div style={{fontSize:13,color:'rgba(0,0,0,0.3)',fontWeight:500}}>Add job for this day</div>
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { ScheduleScreen });
