// MobileView.jsx — operator/rigger phone view
// 3 tabs: Yesterday · Today · Tomorrow
//   Yesterday → read-only history (completed jobs)
//   Today     → today's job(s) with "Submit Completion" CTA
//   Tomorrow  → locked until 7pm (server-side push timing) — toggleable in demo
// No tap-through flow. Operator just sees, does, completes.

function MobileOperatorView({ role = 'Operator', onSign }) {
  const isRigger = role === 'Rigger';
  const [tab, setTab] = React.useState('today');
  // Demo toggle: in real app, server gates this. Here, let user flip between pre-7pm and post-7pm to see both states.
  const [after7pm, setAfter7pm] = React.useState(true);

  // Filter to bookings assigned to "this operator" (Razak Hassan for demo).
  // In production this is the logged-in user.
  const operatorName = isRigger ? 'Ahmad Faizal' : 'Razak Hassan';
  const myBookings = BOOKINGS.filter(b =>
    isRigger ? b.rigger === operatorName : b.operator === operatorName
  );

  const yIso = addDaysISO(TODAY, -1);
  const tIso = TODAY;
  const mIso = addDaysISO(TODAY, 1);
  const shortDate = (iso) => new Date(iso + 'T00:00:00').toLocaleDateString('en-GB', { day: '2-digit', month: 'short' });

  // Always show a day's jobs earliest-first (08:00 before 13:00).
  const byStart = (a, b) => (a.start || '').localeCompare(b.start || '');
  const yesterday = myBookings.filter(b => b.date === yIso).sort(byStart);
  const today     = myBookings.filter(b => b.date === tIso).sort(byStart);
  const tomorrow  = myBookings.filter(b => b.date === mIso).sort(byStart);

  const tabs = [
    { id: 'yesterday', label: 'Yesterday', count: yesterday.length, sub: shortDate(yIso) },
    { id: 'today',     label: 'Today',     count: today.length,     sub: shortDate(tIso) },
    { id: 'tomorrow',  label: 'Tomorrow',  count: tomorrow.length,  sub: shortDate(mIso), locked: !after7pm },
  ];

  const activeJobs = tab === 'yesterday' ? yesterday : tab === 'today' ? today : tomorrow;

  return (
    <div className="content">
      <div style={{display: 'grid', gridTemplateColumns: '1fr auto 1fr', gap: 32, alignItems: 'flex-start'}}>

        {/* Left: explainer */}
        <div style={{maxWidth: 360}}>
          <div className="eyebrow">Mobile · {isRigger ? 'Rigger / Attendant App' : 'Operator App'}</div>
          <h2 style={{fontSize: 28, marginTop: 8, marginBottom: 12}}>Just my jobs.<br/>Nothing else.</h2>
          <p style={{color: 'var(--color-grey-600)'}}>
            {isRigger ? 'Riggers' : 'Operators'} see only their own bookings — yesterday for context, today's work, and tomorrow's plan. No fleet view, no other people's jobs.
          </p>

          <div style={{marginTop: 24, padding: 16, background: 'white', border: '1px solid var(--border-default)', borderRadius: 12}}>
            <div style={{fontSize: 12, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--color-grey-600)', marginBottom: 8}}>The 7pm rule</div>
            <p style={{fontSize: 13, color: 'var(--color-grey-700)', lineHeight: 1.5, margin: 0}}>
              Tomorrow's schedule is pushed to operators at <strong>7:00 PM</strong> each evening. If Admin changes a tomorrow booking after 7pm, the operator gets an instant push: <em>"Tomorrow's job changed — review now."</em>
            </p>
            <div style={{marginTop: 12, padding: 10, background: 'var(--color-grey-50)', borderRadius: 8, fontSize: 12, color: 'var(--color-grey-700)'}}>
              <strong>Demo toggle</strong> — flip to see both states:
              <div style={{display: 'flex', gap: 6, marginTop: 8}}>
                <button
                  className={"radio-chip " + (!after7pm ? 'radio-chip--active' : '')}
                  onClick={() => setAfter7pm(false)}
                  style={{flex: 1, fontSize: 11, padding: '6px 8px'}}>
                  Before 7pm (locked)
                </button>
                <button
                  className={"radio-chip " + (after7pm ? 'radio-chip--active' : '')}
                  onClick={() => setAfter7pm(true)}
                  style={{flex: 1, fontSize: 11, padding: '6px 8px'}}>
                  After 7pm (released)
                </button>
              </div>
            </div>
          </div>
        </div>

        {/* Phone frame */}
        <div className="phone-frame">
          <div className="phone-frame__inner">
            <div className="phone-status">
              <span>9:41</span>
              <span style={{display: 'flex', gap: 4, alignItems: 'center'}}>
                <Signal size={12}/> <Wifi size={12}/> <Battery size={14}/>
              </span>
            </div>

            {/* App header */}
            <div style={{background: 'var(--color-navy)', color: 'white', padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 12}}>
              <img src="assets/powlee-logo.png" alt="Pow Lee" style={{height: 28, width: 'auto', display: 'block'}}/>
              <div style={{flex: 1, minWidth: 0}}>
                <div style={{fontSize: 11, color: 'rgba(255,255,255,0.6)', letterSpacing: '0.1em', textTransform: 'uppercase', fontWeight: 600}}>{isRigger ? 'Rigger' : 'Operator'}</div>
                <div style={{fontWeight: 700, fontSize: 14}}>{operatorName}</div>
              </div>
              <Bell size={18}/>
            </div>

            {/* Day tabs — selected day is wrapped in a solid navy frame so it's the
                first thing the operator sees on a sunlit jobsite. */}
            <div style={{display: 'flex', gap: 6, padding: '10px 10px 8px', background: 'white', borderBottom: '1px solid var(--color-grey-200)'}}>
              {tabs.map(t => {
                const active = tab === t.id;
                return (
                  <button
                    key={t.id}
                    onClick={() => setTab(t.id)}
                    style={{
                      flex: 1, padding: '8px 4px', display: 'flex', flexDirection: 'column',
                      alignItems: 'center', gap: 2, position: 'relative',
                      background: active ? 'var(--color-navy)' : 'white',
                      color: active ? 'white' : 'var(--color-grey-600)',
                      border: active ? '2px solid var(--color-navy)' : '2px solid var(--color-grey-200)',
                      borderRadius: 10,
                      boxShadow: active ? '0 2px 6px rgba(11, 31, 58, 0.25)' : 'none',
                      fontWeight: active ? 700 : 500,
                      cursor: 'pointer',
                    }}>
                    <div style={{fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.06em'}}>{t.label}</div>
                    <div style={{fontSize: 12, fontWeight: active ? 700 : 500}}>{t.sub} · {t.count}</div>
                    {t.locked ? <Lock size={10} style={{position: 'absolute', top: 4, right: 4, opacity: active ? 0.8 : 0.5}}/> : null}
                  </button>
                );
              })}
            </div>

            <div className="phone-content">
              {/* Tomorrow + locked → 7pm gate */}
              {tab === 'tomorrow' && !after7pm ? (
                <div style={{padding: '40px 24px', textAlign: 'center'}}>
                  <div style={{width: 64, height: 64, borderRadius: '50%', background: 'var(--color-grey-100)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 16}}>
                    <Lock size={28} style={{color: 'var(--color-grey-500)'}}/>
                  </div>
                  <div style={{fontSize: 18, fontWeight: 700, color: 'var(--color-navy)', marginBottom: 6}}>Released at 7:00 PM</div>
                  <div style={{fontSize: 13, color: 'var(--color-grey-600)', lineHeight: 1.5}}>
                    Tomorrow's schedule will be pushed to you tonight. You'll get a notification when ready.
                  </div>
                  <div style={{marginTop: 24, padding: 12, background: 'var(--color-grey-50)', borderRadius: 8, fontSize: 12, color: 'var(--color-grey-700)', textAlign: 'left'}}>
                    <Clock size={12} style={{verticalAlign: 'middle'}}/> &nbsp;<strong>Why the delay?</strong> Admin sometimes adjusts tomorrow's jobs late in the day. Locking until 7pm means you don't memorize an out-of-date plan.
                  </div>
                </div>
              ) : null}

              {/* Empty state (yesterday/tomorrow with no jobs) */}
              {activeJobs.length === 0 && !(tab === 'tomorrow' && !after7pm) ? (
                <div style={{padding: '40px 24px', textAlign: 'center', color: 'var(--color-grey-500)'}}>
                  <CalendarIcon size={28} style={{opacity: 0.4, marginBottom: 8}}/>
                  <div style={{fontWeight: 600}}>No jobs {tab === 'yesterday' ? 'yesterday' : tab === 'today' ? 'today' : 'tomorrow'}</div>
                  <div style={{fontSize: 12, marginTop: 4}}>
                    {tab === 'tomorrow' ? 'Rest day — enjoy.' : 'Nothing on schedule.'}
                  </div>
                </div>
              ) : null}

              {/* Jobs list */}
              {activeJobs.length > 0 && !(tab === 'tomorrow' && !after7pm) ? activeJobs.map((order, idx) => (
                <div key={order.id} style={{padding: 16, borderBottom: idx < activeJobs.length - 1 ? '8px solid var(--color-grey-100)' : 'none'}}>

                  <div style={{display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8}}>
                    <span style={{fontFamily: 'monospace', fontSize: 11, color: 'var(--color-grey-500)', fontWeight: 700}}>{order.id}</span>
                    <span style={{fontSize: 12, color: 'var(--color-grey-600)'}}>
                      {order.shift === 'morning' ? '8am – 12pm' : order.shift === 'afternoon' ? '1pm – 5pm' : `${order.start} – ${order.end}`}
                    </span>
                  </div>

                  <div style={{display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 8, margin: '0 0 4px 0'}}>
                    <h3 style={{fontSize: 17, color: 'var(--color-navy)', margin: 0}}>{order.customer}</h3>
                  </div>
                  <div style={{fontSize: 13, color: 'var(--color-grey-600)', display: 'flex', alignItems: 'flex-start', gap: 4, marginBottom: 12}}>
                    <MapPin size={12} style={{marginTop: 2, flexShrink: 0}}/> <span>{order.location}</span>
                  </div>

                  <div style={{background: 'var(--color-grey-50)', borderRadius: 12, padding: 12, marginBottom: 12}}>
                    <div style={{display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10}}>
                      <div>
                        <div style={{fontSize: 10, color: 'var(--color-grey-500)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 700}}>Machine</div>
                        <div style={{fontSize: 12, fontWeight: 600, color: 'var(--color-navy)', marginTop: 2}}>{bookingMachineLabel(order)}</div>
                      </div>
                      <div>
                        <div style={{fontSize: 10, color: 'var(--color-grey-500)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 700}}>{isRigger ? 'Operator' : 'Rigger'}</div>
                        <div style={{fontSize: 12, fontWeight: 600, color: 'var(--color-navy)', marginTop: 2}}>{isRigger ? order.operator : order.rigger}</div>
                      </div>
                      <div style={{gridColumn: '1 / -1'}}>
                        <div style={{fontSize: 10, color: 'var(--color-grey-500)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 700}}>Person in Charge</div>
                        <div style={{fontSize: 12, fontWeight: 600, color: 'var(--color-navy)', marginTop: 2}}>{order.contact || '—'}</div>
                        {order.phone ? (
                          <a href={`tel:${order.phone.replace(/\s/g, '')}`} style={{fontSize: 12, color: 'var(--color-navy)', marginTop: 2, display: 'inline-flex', alignItems: 'center', gap: 4, textDecoration: 'none'}}>
                            <Phone size={11}/> {order.phone}
                          </a>
                        ) : null}
                      </div>
                      {order.remarks ? (
                        <div style={{gridColumn: '1 / -1', paddingTop: 8, borderTop: '1px dashed var(--color-grey-300)'}}>
                          <div style={{fontSize: 10, color: 'var(--color-yellow-700)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 700}}>⚠ Remarks</div>
                          <div style={{fontSize: 12, color: 'var(--color-grey-700)', marginTop: 2}}>{order.remarks}</div>
                        </div>
                      ) : null}
                    </div>
                  </div>

                  <div style={{display: 'flex', flexDirection: 'column', gap: 8, marginBottom: tab === 'today' ? 12 : 0}}>
                    <button className="btn btn--ghost" style={{width: '100%', height: 44, fontSize: 13}}>
                      <Phone size={14}/> Customer
                    </button>
                    <a
                      href={`https://wa.me/${(order.phone || '').replace(/[^0-9]/g, '')}?text=${encodeURIComponent(`Good evening boss ${order.contact || ''}, Could you please share me the job location at ${order.location || ''} tomorrow ? Thank you.\n\nSelamat petang boss ${order.contact || ''}, boleh boss kongsikan lokasi kerja di ${order.location || ''} esok? Terima kasih.`)}`}
                      target="_blank" rel="noopener noreferrer"
                      className="btn"
                      style={{width: '100%', height: 44, fontSize: 13, background: '#25D366', color: 'white', textDecoration: 'none'}}>
                      <WhatsApp size={14}/> WhatsApp for Location
                    </a>
                  </div>

                  {/* Today only: submit completion at end of job */}
                  {tab === 'today' ? (
                    <button className="btn btn--primary btn--lg" style={{width: '100%', height: 52, fontSize: 15, fontWeight: 700}}
                      onClick={() => onSign && onSign(order.id)}>
                      <PenTool size={16}/> Sign
                    </button>
                  ) : null}

                  {/* Yesterday only: read-only checkmark */}
                  {tab === 'yesterday' ? (
                    <div style={{padding: '10px 12px', background: 'rgba(34,197,94,0.1)', color: '#166534', borderRadius: 8, fontWeight: 600, fontSize: 13, textAlign: 'center'}}>
                      <Check size={14} style={{verticalAlign: 'middle'}}/> Job completed
                    </div>
                  ) : null}
                </div>
              )) : null}

              {/* Tomorrow + released — banner */}
              {tab === 'tomorrow' && after7pm && activeJobs.length > 0 ? (
                <div style={{padding: '10px 16px', background: 'rgba(255,213,0,0.15)', color: 'var(--color-navy)', fontSize: 12, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 8, borderBottom: '1px solid var(--color-yellow-700)'}}>
                  <Bell size={14}/> Pushed 7:00 PM · Tap a job to review
                </div>
              ) : null}
            </div>
          </div>
        </div>

        {/* Right: tech notes */}
        <div style={{maxWidth: 280, fontSize: 13, color: 'var(--color-grey-600)'}}>
          <div className="eyebrow">How it works</div>
          <ul style={{paddingLeft: 18, marginTop: 12, lineHeight: 1.7}}>
            <li><strong>Yesterday tab:</strong> last 24h of completed jobs — read-only, useful for follow-up calls or fixing paperwork.</li>
            <li><strong>Today tab:</strong> current jobs. Tap <em>Submit Completion</em> at the end of the day to capture customer sign-off.</li>
            <li><strong>Tomorrow tab:</strong> locked until 7pm. Admin's daily finalisation cut-off.</li>
            <li><strong>Live push:</strong> if Admin edits a tomorrow job after 7pm, operator gets an instant notification.</li>
          </ul>

          <div style={{marginTop: 20}}>
            <div className="eyebrow">No status taps</div>
            <p style={{marginTop: 8, lineHeight: 1.55, color: 'var(--color-grey-600)'}}>
              Operators don't tap "Accepted / On the Way / Arrived". A booking just exists. The assigned machine flips from <span className="mdot mdot--available" style={{margin: '0 4px', verticalAlign: 'middle'}}/> available → <span className="mdot mdot--occupied" style={{margin: '0 4px', verticalAlign: 'middle'}}/> booked, and back when completion is submitted.
            </p>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { MobileOperatorView });
