/* global React, FoodPhoto, TimerRing, SubHead, Confirm */
const { useState: useStateK, useEffect: useEffectK } = React;

// ============================================================
// KITCHEN PRESENTER
// ============================================================
const KITCHEN_TASKS_INIT = [
  { id:'k1', name:'HOT & CRISPY', hi:'हॉट एंड क्रिस्पी', qty:12, total:480, remaining:120, sub:'BUCKET PREP' },
  { id:'k2', name:'ZINGER BURGER', hi:'ज़िंगर बर्गर', qty:8, total:300, remaining:230, sub:'GRILL' },
  { id:'k3', name:'POPCORN CHICKEN', hi:'पॉपकॉर्न चिकन', qty:20, total:240, remaining:30, sub:'FRYER 2' },
  { id:'k4', name:'CHICKEN TENDERS', hi:'चिकन टेंडर्स', qty:6, total:360, remaining:280, sub:'FRYER 1' },
  { id:'k5', name:'HOT WINGS', hi:'हॉट विंग्स', qty:14, total:420, remaining:380, sub:'FRYER 2' },
  { id:'k6', name:'VEG ZINGER', hi:'वेज ज़िंगर', qty:4, total:300, remaining:160, sub:'GRILL' },
];

function KitchenScreen({ onBack }) {
  const [tasks, setTasks] = useStateK(KITCHEN_TASKS_INIT);
  useEffectK(() => {
    const id = setInterval(() => {
      setTasks(t => t.map(x => ({...x, remaining: Math.max(0, x.remaining - 1)})));
    }, 1000);
    return () => clearInterval(id);
  }, []);
  const sorted = [...tasks].sort((a,b)=>a.remaining-b.remaining);
  const top = sorted.slice(0,6);
  const queued = [
    { num:'1048', name:'Family Bucket', qty:'×1' },
    { num:'1049', name:'Krushers Mango', qty:'×3' },
    { num:'1050', name:'Rice Bowl Spicy', qty:'×2' },
    { num:'1051', name:'Boneless 6pc', qty:'×1' },
    { num:'1052', name:'Coleslaw', qty:'×4' },
    { num:'1053', name:'Pepsi 500', qty:'×6' },
  ];
  return (
    <div className="view view-enter">
      <SubHead onBack={onBack} en="KITCHEN PRESENTER" hi="किचन प्रस्तुतकर्ता"
        stats={[
          {v: top.length, l:'COOKING'},
          {v: top.filter(t=>t.remaining<60).length, l:'URGENT', urgent:true},
          {v: '94%', l:'ON TIME'},
        ]}/>
      <div className="kitchen">
        <div className="cook-grid">
          {top.map(t => {
            const pct = t.remaining / t.total;
            const cls = pct < 0.2 ? 'urgent' : '';
            return (
              <div key={t.id} className={"cook-card " + cls}>
                <FoodPhoto className="photo" name={t.name} sub={t.sub} />
                <div className="row">
                  <div>
                    <div className="name">{t.name}</div>
                    <div className="name-hi">{t.hi}</div>
                  </div>
                  <div className="qty">×{t.qty}<small>QTY</small></div>
                </div>
                <div className="footer">
                  <TimerRing remaining={t.remaining} total={t.total} />
                  <button className="btn-done" onClick={() => setTasks(s => s.filter(x=>x.id!==t.id))}>
                    <span className="material-symbols-rounded">check_circle</span>
                    DONE <span className="hindi-text">/ पूरा</span>
                  </button>
                </div>
              </div>
            );
          })}
        </div>
        <div className="cook-strip">
          <div className="title">▸ UPCOMING <span className="hindi-text">/ आगामी कार्य</span> · {queued.length} TASKS</div>
          <div className="row">
            {queued.map((q,i)=>(
              <div key={i} className="queue-tile">
                <div className="ord">{i+1}</div>
                <div>
                  <div className="qt-name">{q.name}</div>
                  <div className="qt-qty">ORD #{q.num} · {q.qty}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

// ============================================================
// DISTRIBUTION
// ============================================================
const ROLES = [
  { id:'foh', en:'FOH', name:'FRONT OF HOUSE', hi:'फ्रंट / कैशियर', icon:'point_of_sale',
    stats:[{v:3,l:'ON COUNTER'},{v:'2:18',l:'AVG WAIT'}] },
  { id:'moh', en:'MOH', name:'MIDDLE OF HOUSE', hi:'मध्य / पास-थ्रू', icon:'pan_tool',
    stats:[{v:5,l:'IN PASS'},{v:7,l:'PACKING'}] },
  { id:'boh', en:'BOH', name:'BACK OF HOUSE', hi:'बैक / किचन', icon:'oven_gen',
    stats:[{v:9,l:'ON LINE'},{v:'82°C',l:'OIL TEMP'}] },
];

const QA_BUTTONS = [
  { id:'fryer', en:'TURN OFF FRYER', hi:'फ्रायर बंद', icon:'local_fire_department', cls:'danger' },
  { id:'grill', en:'TURN OFF GRILL', hi:'ग्रिल बंद', icon:'outdoor_grill', cls:'danger' },
  { id:'mgr',   en:'CALL MANAGER', hi:'प्रबंधक बुलाएँ', icon:'support_agent', cls:'' },
  { id:'cust',  en:'CUSTOMER ALERT', hi:'ग्राहक प्रतीक्षा', icon:'priority_high', cls:'warn' },
  { id:'clean', en:'CLEANING', hi:'सफाई आवश्यक', icon:'cleaning_services', cls:'' },
];

function DistributionScreen({ onBack }) {
  const [role, setRole] = useStateK(null);
  const [confirm, setConfirm] = useStateK(null);

  return (
    <div className="view view-enter">
      <SubHead onBack={() => role ? setRole(null) : onBack()}
        en={role ? `${role.en} STATION` : 'HOUSE DISTRIBUTION'}
        hi={role ? role.hi : 'घर वितरण / स्टेशन चुनें'}
        stats={role ? [{v:'12', l:'TASKS'},{v:'0', l:'OVERDUE'}] : [{v:'5',l:'STATIONS'},{v:'12',l:'STAFF'}]} />

      <div className="dist">
        <div className="dist-main">
          {!role ? (
            <div className="role-grid">
              {ROLES.map(r => (
                <div key={r.id} className="role-tile press" onClick={()=>setRole(r)}>
                  <div className="top">
                    <div className="ic-big"><span className="material-symbols-rounded">{r.icon}</span></div>
                    <div className="role-en">{r.en}</div>
                    <div className="role-name">{r.name}</div>
                    <div className="role-hi">{r.hi}</div>
                  </div>
                  <div className="bot">
                    {r.stats.map((s,i)=>(
                      <div key={i} className="stat-grp">
                        <strong>{s.v}</strong>
                        <small>{s.l}</small>
                      </div>
                    ))}
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <StationBoard role={role} />
          )}
        </div>

        <aside className="siderail">
          <div className="siderail-head">QUICK <span className="hindi-text">· त्वरित</span></div>
          {QA_BUTTONS.map(q => (
            <button key={q.id} className={"qa-btn " + q.cls} onClick={()=>setConfirm(q)}>
              <span className="material-symbols-rounded">{q.icon}</span>
              <div className="lbl">{q.en}</div>
              <div className="hi">{q.hi}</div>
            </button>
          ))}
        </aside>
      </div>

      {confirm && (
        <Confirm
          danger={confirm.cls==='danger'}
          title={confirm.en}
          hi={confirm.hi}
          body="Confirm this action — staff will be alerted."
          onYes={()=>setConfirm(null)}
          onNo={()=>setConfirm(null)}
        />
      )}
    </div>
  );
}

function StationBoard({ role }) {
  const tasksByRole = {
    foh: [
      { name:'COUNTER PACK', hi:'काउंटर पैकिंग', sub:'ORD #1042', t:120, total:180 },
      { name:'TAKEAWAY BAG', hi:'टेकअवे बैग', sub:'ORD #1047', t:240, total:300 },
      { name:'CONDIMENT KIT', hi:'सॉस किट', sub:'ORD #1048', t:60, total:120 },
      { name:'BEVERAGE FILL', hi:'पेय भरें', sub:'ORD #1042', t:30, total:90 },
    ],
    moh: [
      { name:'BUCKET ASSEMBLY', hi:'बकेट असेंबली', sub:'ORD #1043', t:150, total:300 },
      { name:'BURGER WRAP', hi:'बर्गर रैप', sub:'ORD #1044', t:90, total:180 },
      { name:'TENDER PACK', hi:'टेंडर पैक', sub:'ORD #1045', t:200, total:240 },
      { name:'COMBO TRAY', hi:'कॉम्बो ट्रे', sub:'ORD #1046', t:60, total:180 },
    ],
    boh: [
      { name:'FRYER LOAD', hi:'फ्रायर लोड', sub:'BATCH 14', t:180, total:240 },
      { name:'GRILL TURN', hi:'ग्रिल पलटें', sub:'BATCH 12', t:30, total:120 },
      { name:'BREADING', hi:'ब्रेडिंग', sub:'BATCH 15', t:300, total:420 },
      { name:'OIL FILTER', hi:'तेल फिल्टर', sub:'FRYER 2', t:600, total:900 },
    ]
  };
  const tasks = tasksByRole[role.id];
  return (
    <div className="station-board">
      {tasks.map((t,i)=>(
        <div key={i} className="station-card">
          <FoodPhoto className="photo" name={t.name} sub={t.sub} />
          <div className="info">
            <div className="name">{t.name}</div>
            <div className="name-hi">{t.hi}</div>
            <div className="meta">{t.sub}</div>
          </div>
          <TimerRing remaining={t.t} total={t.total} />
        </div>
      ))}
    </div>
  );
}

Object.assign(window, { KitchenScreen, DistributionScreen });
