/* global React, ReactDOM, TopBar, SubHead, firebase, QRCode, Html5Qrcode */
const {
  useEffect: useEffectPacket,
  useMemo: useMemoPacket,
  useRef: useRefPacket,
  useState: useStatePacket,
} = React;

const PACKET_AUTH = {
  username: 'KFC',
  password: 'ardh',
  performedBy: 'KFC_MANAGER_FRONTEND',
};

const PACKET_FIREBASE_CONFIG = {
  apiKey: 'AIzaSyDssh29oknSJrAicJHM22sXQOBkVQiqx9k',
  authDomain: 'ardh-kfc.firebaseapp.com',
  projectId: 'ardh-kfc',
  storageBucket: 'ardh-kfc.firebasestorage.app',
  messagingSenderId: '253199959698',
  appId: '1:253199959698:web:b0bd3079c6b06e1a45884b',
  measurementId: 'G-QYTEPL88WG',
};

const PACKET_SOURCE_PAGE = 'Packet QR / MRD Management';

const PACKET_STATUS = {
  PRINTED_NOT_RECEIVED: 'printed_not_received',
  IN_INVENTORY: 'in_inventory',
  IN_MARINATION: 'in_marination',
  MARINATED_MRD_PRINTED: 'marinated_mrd_printed',
  DISCARDED: 'discarded',
};

const SKU_CATALOG = [
  {
    skuId: 'hot-crispy-full-packet',
    displayName: 'Hot & Crispy Full Packet',
    defaultPacketSize: 'Standard packet',
    shelfLifeDays: 2,
    shelfLifeHours: 48,
    isMarinationEligible: true,
    canPrintBaseMRD: true,
    canPrintMarinatedMRD: true,
  },
  {
    skuId: 'popcorn',
    displayName: 'Popcorn',
    defaultPacketSize: 'Standard packet',
    shelfLifeDays: 2,
    shelfLifeHours: 48,
    isMarinationEligible: true,
    canPrintBaseMRD: true,
    canPrintMarinatedMRD: true,
  },
  {
    skuId: 'zinger-fillet',
    displayName: 'Zinger Fillet',
    defaultPacketSize: 'Standard packet',
    shelfLifeDays: 2,
    shelfLifeHours: 48,
    isMarinationEligible: true,
    canPrintBaseMRD: true,
    canPrintMarinatedMRD: true,
  },
  {
    skuId: 'hot-wings',
    displayName: 'Hot Wings',
    defaultPacketSize: 'Standard packet',
    shelfLifeDays: 2,
    shelfLifeHours: 48,
    isMarinationEligible: true,
    canPrintBaseMRD: true,
    canPrintMarinatedMRD: true,
  },
  {
    skuId: 'whole-leg',
    displayName: 'Whole Leg',
    defaultPacketSize: 'Standard packet',
    shelfLifeDays: 2,
    shelfLifeHours: 48,
    isMarinationEligible: true,
    canPrintBaseMRD: true,
    canPrintMarinatedMRD: true,
  },
  {
    skuId: 'supreme-fillet',
    displayName: 'Supreme Fillet',
    defaultPacketSize: 'Standard packet',
    shelfLifeDays: 2,
    shelfLifeHours: 48,
    isMarinationEligible: true,
    canPrintBaseMRD: true,
    canPrintMarinatedMRD: true,
  },
  {
    skuId: 'chicken-drum-leg',
    displayName: 'Chicken Drum Leg',
    defaultPacketSize: 'Standard packet',
    shelfLifeDays: 2,
    shelfLifeHours: 48,
    isMarinationEligible: true,
    canPrintBaseMRD: true,
    canPrintMarinatedMRD: true,
  },
];

const SKU_BY_ID = SKU_CATALOG.reduce((map, sku) => Object.assign(map, { [sku.skuId]: sku }), {});

let packetFirebaseApp;
let packetAuthPromise;

async function getPacketDb() {
  if (!window.firebase || !firebase.firestore) {
    throw new Error('Firebase SDK is not loaded.');
  }
  if (!packetFirebaseApp) {
    packetFirebaseApp = firebase.apps.length
      ? firebase.app()
      : firebase.initializeApp(PACKET_FIREBASE_CONFIG);
  }
  if (firebase.auth && !packetAuthPromise) {
    const auth = firebase.auth(packetFirebaseApp);
    packetAuthPromise = auth.currentUser
      ? Promise.resolve(auth.currentUser)
      : auth.signInAnonymously()
        .then((credential) => credential.user)
        .catch((err) => {
          throw new Error(`Firebase anonymous auth failed: ${err.message || err.code || 'Enable Anonymous sign-in or update Firestore rules.'}`);
        });
  }
  if (packetAuthPromise) await packetAuthPromise;
  return firebase.firestore(packetFirebaseApp);
}

function nowIso() {
  return new Date().toISOString();
}

function addHoursIso(iso, hours) {
  return new Date(new Date(iso).getTime() + Number(hours || 0) * 60 * 60 * 1000).toISOString();
}

function formatDateTime(iso) {
  if (!iso) return 'Not set';
  const d = new Date(iso);
  if (Number.isNaN(d.getTime())) return 'Invalid time';
  return d.toLocaleString([], {
    year: 'numeric',
    month: 'short',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  });
}

function shortCode(id) {
  if (!id) return '';
  return id.slice(-8).toUpperCase();
}

function makePacketId(prefix, skuId) {
  const ts = Date.now().toString(36).toUpperCase();
  const rand = Math.random().toString(36).slice(2, 7).toUpperCase();
  return `${prefix}-${skuId.toUpperCase().replace(/[^A-Z0-9]+/g, '-')}-${ts}-${rand}`;
}

function makeQrPayload(packetOrId) {
  if (typeof packetOrId === 'string') {
    return JSON.stringify({ v: 1, type: 'kfc_packet', packetId: packetOrId });
  }
  const packet = packetOrId || {};
  return JSON.stringify({
    v: 1,
    type: 'kfc_packet',
    uniquePacketId: packet.uniquePacketId || packet.marinatedPacketId,
    skuId: packet.skuId,
    skuName: packet.skuName,
    packetType: packet.packetType || 'base',
    mrdStartAt: packet.marinatedMrdStartAt || packet.mrdStartAt || packet.createdAt,
    shelfLifeHours: packet.shelfLifeHours,
    createdAt: packet.createdAt,
    status: packet.status,
  });
}

function parsePacketQr(raw) {
  const value = String(raw || '').trim();
  if (!value) throw new Error('The QR code is empty.');
  try {
    const parsed = JSON.parse(value);
    const packetId = parsed.packetId || parsed.uniquePacketId || parsed.marinatedPacketId;
    if (packetId) return packetId;
  } catch (e) {}
  if (/^(PKT|MRN|BASE|MAR)-[A-Z0-9-]+$/i.test(value)) return value;
  throw new Error('This QR is not a KFC packet QR.');
}

function eventDoc(db) {
  const ref = db.collection('inventoryEvents').doc();
  return {
    ref,
    eventId: ref.id,
  };
}

function eventPayload({ eventId, packetId, parentPacketId, skuId, eventType, previousStatus, newStatus }) {
  return {
    eventId,
    packetId,
    parentPacketId: parentPacketId || null,
    skuId,
    eventType,
    previousStatus: previousStatus || null,
    newStatus: newStatus || null,
    timestamp: firebase.firestore.FieldValue.serverTimestamp(),
    performedBy: PACKET_AUTH.performedBy,
    sourcePage: PACKET_SOURCE_PAGE,
  };
}

async function createPacketRecord(sku) {
  const db = await getPacketDb();
  const uniquePacketId = makePacketId('PKT', sku.skuId);
  const createdAt = nowIso();
  const record = {
    uniquePacketId,
    skuId: sku.skuId,
    skuName: sku.displayName,
    packetType: 'base',
    mrdStartAt: createdAt,
    shelfLifeHours: sku.shelfLifeHours,
    createdAt,
    receivedAt: null,
    discardAt: null,
    inventoryExitedAt: null,
    marinationStartedAt: null,
    status: PACKET_STATUS.PRINTED_NOT_RECEIVED,
  };
  const packetRef = db.collection('packets').doc(uniquePacketId);
  const evt = eventDoc(db);
  await db.runTransaction(async (tx) => {
    tx.set(packetRef, record);
    tx.set(evt.ref, eventPayload({
      eventId: evt.eventId,
      packetId: uniquePacketId,
      skuId: sku.skuId,
      eventType: 'BASE_MRD_PRINTED',
      previousStatus: null,
      newStatus: PACKET_STATUS.PRINTED_NOT_RECEIVED,
    }));
  });
  return record;
}

async function getPacketById(packetId) {
  const db = await getPacketDb();
  const snap = await db.collection('packets').doc(packetId).get();
  if (!snap.exists) return null;
  return snap.data();
}

async function receivePacketIntoInventory(packet) {
  const db = await getPacketDb();
  const packetRef = db.collection('packets').doc(packet.uniquePacketId);
  const receivedAt = nowIso();
  const shelfLifeHours = packet.shelfLifeHours || SKU_BY_ID[packet.skuId]?.shelfLifeHours;
  if (!shelfLifeHours) throw new Error('Missing shelf life configuration for this SKU.');
  const discardAt = addHoursIso(receivedAt, shelfLifeHours);
  const evt = eventDoc(db);
  await db.runTransaction(async (tx) => {
    const snap = await tx.get(packetRef);
    if (!snap.exists) throw new Error('Packet was not found in Firebase.');
    const current = snap.data();
    if (current.status !== PACKET_STATUS.PRINTED_NOT_RECEIVED) {
      throw new Error(`Packet is currently ${current.status}; it cannot be received again.`);
    }
    tx.update(packetRef, {
      status: PACKET_STATUS.IN_INVENTORY,
      receivedAt,
      discardAt,
    });
    tx.set(evt.ref, eventPayload({
      eventId: evt.eventId,
      packetId: packet.uniquePacketId,
      skuId: packet.skuId,
      eventType: 'RECEIVED_INTO_INVENTORY',
      previousStatus: PACKET_STATUS.PRINTED_NOT_RECEIVED,
      newStatus: PACKET_STATUS.IN_INVENTORY,
    }));
  });
  return Object.assign({}, packet, { status: PACKET_STATUS.IN_INVENTORY, receivedAt, discardAt });
}

async function movePacketToMarination(packet) {
  const db = await getPacketDb();
  const packetRef = db.collection('packets').doc(packet.uniquePacketId);
  const movedAt = nowIso();
  const evt = eventDoc(db);
  await db.runTransaction(async (tx) => {
    const snap = await tx.get(packetRef);
    if (!snap.exists) throw new Error('Packet was not found in Firebase.');
    const current = snap.data();
    if (current.status !== PACKET_STATUS.IN_INVENTORY) {
      throw new Error(`Packet is currently ${current.status}; it cannot exit inventory.`);
    }
    tx.update(packetRef, {
      status: PACKET_STATUS.IN_MARINATION,
      marinationStartedAt: movedAt,
      inventoryExitedAt: movedAt,
    });
    tx.set(evt.ref, eventPayload({
      eventId: evt.eventId,
      packetId: packet.uniquePacketId,
      skuId: packet.skuId,
      eventType: 'EXITED_INVENTORY_TO_MARINATION',
      previousStatus: PACKET_STATUS.IN_INVENTORY,
      newStatus: PACKET_STATUS.IN_MARINATION,
    }));
  });
  return Object.assign({}, packet, {
    status: PACKET_STATUS.IN_MARINATION,
    marinationStartedAt: movedAt,
    inventoryExitedAt: movedAt,
  });
}

async function listPacketsEligibleForMarinatedMrd() {
  const db = await getPacketDb();
  const snap = await db.collection('packets')
    .where('status', '==', PACKET_STATUS.IN_MARINATION)
    .get();
  return snap.docs
    .map((doc) => doc.data())
    .filter((packet) => {
      const sku = SKU_BY_ID[packet.skuId];
      return sku && sku.isMarinationEligible && sku.canPrintMarinatedMRD;
    })
    .sort((a, b) => String(b.marinationStartedAt || '').localeCompare(String(a.marinationStartedAt || '')));
}

async function createMarinatedMrdRecord(parentPacket) {
  const sku = SKU_BY_ID[parentPacket.skuId];
  if (!sku || !sku.canPrintMarinatedMRD || !sku.isMarinationEligible) {
    throw new Error('This SKU is not eligible for marinated QR/MRD printing.');
  }
  const db = await getPacketDb();
  const marinatedPacketId = makePacketId('MRN', sku.skuId);
  const createdAt = nowIso();
  const parentRef = db.collection('packets').doc(parentPacket.uniquePacketId);
  const childRef = db.collection('packets').doc(marinatedPacketId);
  const evt = eventDoc(db);
  const childRecord = {
    uniquePacketId: marinatedPacketId,
    marinatedPacketId,
    parentPacketId: parentPacket.uniquePacketId,
    skuId: sku.skuId,
    skuName: sku.displayName,
    packetType: 'marinated',
    mrdStartAt: createdAt,
    marinatedMrdStartAt: createdAt,
    shelfLifeHours: sku.shelfLifeHours,
    createdAt,
    receivedAt: null,
    discardAt: null,
    inventoryExitedAt: null,
    marinationStartedAt: parentPacket.marinationStartedAt || null,
    status: PACKET_STATUS.MARINATED_MRD_PRINTED,
  };
  await db.runTransaction(async (tx) => {
    const parentSnap = await tx.get(parentRef);
    if (!parentSnap.exists) throw new Error('Parent packet was not found in Firebase.');
    const current = parentSnap.data();
    if (current.status !== PACKET_STATUS.IN_MARINATION) {
      throw new Error(`Parent packet is currently ${current.status}; marinated MRD cannot be printed.`);
    }
    tx.set(childRef, childRecord);
    tx.update(parentRef, {
      status: PACKET_STATUS.MARINATED_MRD_PRINTED,
      marinatedPacketId,
      marinatedMrdPrintedAt: createdAt,
    });
    tx.set(evt.ref, eventPayload({
      eventId: evt.eventId,
      packetId: marinatedPacketId,
      parentPacketId: parentPacket.uniquePacketId,
      skuId: sku.skuId,
      eventType: 'MARINATED_MRD_PRINTED',
      previousStatus: PACKET_STATUS.IN_MARINATION,
      newStatus: PACKET_STATUS.MARINATED_MRD_PRINTED,
    }));
  });
  return childRecord;
}

function QrCodeBlock({ value, size = 176 }) {
  const qrRef = useRefPacket(null);
  useEffectPacket(() => {
    if (!qrRef.current || !value || !window.QRCode) return;
    qrRef.current.innerHTML = '';
    new QRCode(qrRef.current, {
      text: value,
      width: size,
      height: size,
      correctLevel: QRCode.CorrectLevel.M,
    });
  }, [value, size]);
  return <div className="packet-qr-box" ref={qrRef} aria-label="Packet QR code"></div>;
}

function StatusPill({ status }) {
  const cls = status === PACKET_STATUS.IN_INVENTORY
    ? 'ready'
    : status === PACKET_STATUS.PRINTED_NOT_RECEIVED || status === PACKET_STATUS.IN_MARINATION
      ? 'warn'
      : status === PACKET_STATUS.DISCARDED
        ? 'urgent'
        : 'off';
  return <span className={`pill ${cls}`}><span className="dot"></span>{String(status || 'unknown').replace(/_/g, ' ')}</span>;
}

function PacketSticker({ packet }) {
  if (!packet) return null;
  const qrValue = makeQrPayload(packet);
  const isMarinated = packet.packetType === 'marinated';
  const displayDiscard = packet.discardAt || (isMarinated ? addHoursIso(packet.marinatedMrdStartAt || packet.createdAt, packet.shelfLifeHours) : null);
  return (
    <div className="packet-sticker" id="packet-print-sticker">
      <div className="packet-sticker-head">
        <div className="packet-sticker-logo">KFC</div>
        <div className="packet-sticker-tag">{isMarinated ? 'MARINATED MRD' : 'PACKET QR MRD'}</div>
      </div>
      <div className="packet-sticker-name">{packet.skuName}</div>
      <div className="packet-sticker-code">ID: {shortCode(packet.uniquePacketId || packet.marinatedPacketId)}</div>
      <div className="packet-sticker-grid">
        <div>
          <div className="packet-sticker-label">MRD Start</div>
          <strong>{formatDateTime(packet.marinatedMrdStartAt || packet.mrdStartAt || packet.createdAt)}</strong>
        </div>
        <div>
          <div className="packet-sticker-label">Discard</div>
          <strong>{displayDiscard ? formatDateTime(displayDiscard) : `Set at inventory scan (+${packet.shelfLifeHours}h)`}</strong>
        </div>
      </div>
      <div className="packet-sticker-qr-row">
        <QrCodeBlock value={qrValue} size={178} />
        <div className="packet-sticker-meta">
          <strong>{packet.packetType || 'base'} packet</strong>
          <span>Standard packet size</span>
          <span>Status: {String(packet.status || '').replace(/_/g, ' ')}</span>
          {packet.parentPacketId && <span>Parent: {shortCode(packet.parentPacketId)}</span>}
          <span>Scan before inventory or marination movement.</span>
        </div>
      </div>
    </div>
  );
}

function PacketDetailRows({ packet }) {
  return (
    <div className="packet-detail-grid">
      <div><span>Product / SKU</span><strong>{packet.skuName}</strong></div>
      <div><span>Unique packet ID</span><strong>{packet.uniquePacketId || packet.marinatedPacketId}</strong></div>
      <div><span>MRD start time</span><strong>{formatDateTime(packet.mrdStartAt || packet.marinatedMrdStartAt || packet.createdAt)}</strong></div>
      <div><span>Discard time</span><strong>{formatDateTime(packet.discardAt)}</strong></div>
      <div><span>Current status</span><strong><StatusPill status={packet.status} /></strong></div>
      <div><span>Packet size</span><strong>{SKU_BY_ID[packet.skuId]?.defaultPacketSize || 'Standard packet'}</strong></div>
    </div>
  );
}

function ModeCards({ mode, onMode }) {
  return (
    <div className="packet-mode-grid">
      <button className={`packet-mode-card ${mode === 'scanner' ? 'active' : ''}`} onClick={() => onMode('scanner')}>
        <div className="ic"><span className="material-symbols-rounded">qr_code_scanner</span></div>
        <div>
          <strong>Scanner</strong>
          <span>Receive packet QR or move inventory to marination</span>
        </div>
        <span className="material-symbols-rounded arrow">arrow_forward</span>
      </button>
      <button className={`packet-mode-card ${mode === 'print' ? 'active' : ''}`} onClick={() => onMode('print')}>
        <div className="ic gold"><span className="material-symbols-rounded">print</span></div>
        <div>
          <strong>QR-MRD / MRD Print</strong>
          <span>Generate base packet and marinated QR/MRD labels</span>
        </div>
        <span className="material-symbols-rounded arrow">arrow_forward</span>
      </button>
    </div>
  );
}

function ScannerPanel() {
  const [login, setLogin] = useStatePacket({ username: '', password: '' });
  const [authorized, setAuthorized] = useStatePacket(false);
  const [loginError, setLoginError] = useStatePacket('');
  const [cameraError, setCameraError] = useStatePacket('');
  const [scanState, setScanState] = useStatePacket('idle');
  const [scanMessage, setScanMessage] = useStatePacket('');
  const [packet, setPacket] = useStatePacket(null);
  const [action, setAction] = useStatePacket(null);
  const [busy, setBusy] = useStatePacket(false);
  const [manualQr, setManualQr] = useStatePacket('');
  const scannerRef = useRefPacket(null);
  const scanLockedRef = useRefPacket(false);

  const stopScanner = async () => {
    const scanner = scannerRef.current;
    if (!scanner) return;
    try {
      await scanner.stop();
      await scanner.clear();
    } catch (e) {}
    scannerRef.current = null;
  };

  const resumeScanner = () => {
    scanLockedRef.current = false;
    const scanner = scannerRef.current;
    try {
      if (scanner && scanner.resume) scanner.resume();
    } catch (e) {}
  };

  const resetScan = () => {
    setPacket(null);
    setAction(null);
    setScanState('ready');
    setScanMessage('Ready for next packet QR.');
    resumeScanner();
  };

  const resolveScan = async (decodedText) => {
    if (scanLockedRef.current || busy) return;
    scanLockedRef.current = true;
    setBusy(true);
    setScanState('loading');
    setScanMessage('Reading QR and checking Firebase...');
    try {
      const packetId = parsePacketQr(decodedText);
      const record = await getPacketById(packetId);
      if (!record) throw new Error('QR packet ID was not found in Firebase.');
      setPacket(record);
      if (record.status === PACKET_STATUS.PRINTED_NOT_RECEIVED) {
        setAction('receive');
        setScanState('confirm');
        setScanMessage('Enter this packet into inventory?');
      } else if (record.status === PACKET_STATUS.IN_INVENTORY) {
        setAction('marination');
        setScanState('confirm');
        setScanMessage('Move this packet out of inventory to marination?');
      } else if (record.status === PACKET_STATUS.IN_MARINATION) {
        setAction(null);
        setScanState('info');
        setScanMessage('This packet has already exited inventory and is in marination.');
      } else if (record.status === PACKET_STATUS.DISCARDED) {
        setAction(null);
        setScanState('error');
        setScanMessage('This packet is already marked discarded.');
      } else {
        setAction(null);
        setScanState('info');
        setScanMessage(`No scanner action is available for status: ${record.status}.`);
      }
      try {
        const scanner = scannerRef.current;
        if (scanner && scanner.pause) scanner.pause(true);
      } catch (e) {}
    } catch (err) {
      setPacket(null);
      setAction(null);
      setScanState('error');
      setScanMessage(err.message || 'Invalid QR code.');
      window.setTimeout(() => {
        if (!packet) {
          scanLockedRef.current = false;
          try {
            const scanner = scannerRef.current;
            if (scanner && scanner.resume) scanner.resume();
          } catch (e) {}
        }
      }, 1400);
    } finally {
      setBusy(false);
    }
  };

  useEffectPacket(() => {
    if (!authorized || !window.Html5Qrcode) return undefined;
    let cancelled = false;
    const start = async () => {
      setCameraError('');
      setScanState('loading');
      setScanMessage('Opening camera scanner...');
      await stopScanner();
      if (cancelled) return;
      const scanner = new Html5Qrcode('packet-qr-reader');
      scannerRef.current = scanner;
      try {
        await scanner.start(
          { facingMode: 'environment' },
          { fps: 10, qrbox: { width: 260, height: 260 } },
          resolveScan,
          () => {}
        );
        if (!cancelled) {
          setScanState('ready');
          setScanMessage('Camera active. Scan a packet QR.');
        }
      } catch (err) {
        if (!cancelled) {
          setScanState('error');
          setCameraError(err.message || 'Camera permission denied or camera unavailable.');
          setScanMessage('Camera could not be opened.');
        }
      }
    };
    start();
    return () => {
      cancelled = true;
      stopScanner();
    };
  }, [authorized]);

  const submitLogin = (e) => {
    e.preventDefault();
    if (login.username === PACKET_AUTH.username && login.password === PACKET_AUTH.password) {
      setLoginError('');
      setAuthorized(true);
    } else {
      setLoginError('Invalid username or password.');
    }
  };

  const confirmAction = async () => {
    if (!packet || !action || busy) return;
    setBusy(true);
    setScanState('loading');
    setScanMessage('Updating Firebase...');
    try {
      const updated = action === 'receive'
        ? await receivePacketIntoInventory(packet)
        : await movePacketToMarination(packet);
      setPacket(updated);
      setAction(null);
      setScanState('success');
      setScanMessage(action === 'receive'
        ? 'Packet entered into inventory.'
        : 'Packet exited inventory and moved to marination.');
    } catch (err) {
      setScanState('error');
      setScanMessage(err.message || 'Firebase write failed.');
    } finally {
      setBusy(false);
    }
  };

  if (!authorized) {
    return (
      <section className="packet-workspace scanner-login">
        <div className="packet-panel narrow">
          <div className="packet-panel-head">
            <span className="material-symbols-rounded">lock</span>
            <div>
              <h2>Scanner Login</h2>
              <p>Camera access opens only after manager login.</p>
            </div>
          </div>
          <form className="packet-login-form" onSubmit={submitLogin}>
            <label>
              Username
              <input value={login.username} onChange={(e) => setLogin((v) => Object.assign({}, v, { username: e.target.value }))} autoComplete="username" />
            </label>
            <label>
              Password
              <input type="password" value={login.password} onChange={(e) => setLogin((v) => Object.assign({}, v, { password: e.target.value }))} autoComplete="current-password" />
            </label>
            {loginError && <div className="packet-alert error">{loginError}</div>}
            <button className="packet-primary-btn" type="submit">
              <span className="material-symbols-rounded">qr_code_scanner</span>
              Open Scanner
            </button>
          </form>
        </div>
      </section>
    );
  }

  return (
    <section className="packet-workspace scanner-grid">
      <div className="packet-panel camera-panel">
        <div className="packet-panel-head">
          <span className="material-symbols-rounded">qr_code_scanner</span>
          <div>
            <h2>Packet QR Scanner</h2>
            <p>Scan once to receive. Scan again to exit inventory for marination.</p>
          </div>
        </div>
        <div id="packet-qr-reader" className="packet-camera-box"></div>
        {cameraError && <div className="packet-alert error">{cameraError}</div>}
        <div className="manual-scan">
          <input placeholder="Manual packet QR payload or packet ID" value={manualQr} onChange={(e) => setManualQr(e.target.value)} />
          <button onClick={() => resolveScan(manualQr)} disabled={!manualQr || busy}>
            <span className="material-symbols-rounded">keyboard</span>
            Check
          </button>
        </div>
      </div>

      <div className="packet-panel result-panel">
        <div className={`scan-state ${scanState}`}>
          <span className="material-symbols-rounded">
            {scanState === 'success' ? 'check_circle' : scanState === 'error' ? 'error' : scanState === 'loading' ? 'hourglass_top' : 'fact_check'}
          </span>
          <strong>{scanMessage || 'Waiting for packet QR.'}</strong>
        </div>
        {packet && (
          <div className="packet-confirm-card">
            <PacketDetailRows packet={packet} />
            {action && (
              <div className="packet-action-box">
                <h3>{action === 'receive' ? 'Enter Inventory?' : 'Move to Marination / Exit Inventory?'}</h3>
                <div className="packet-action-row">
                  <button className="packet-secondary-btn" onClick={resetScan} disabled={busy}>
                    <span className="material-symbols-rounded">close</span>
                    No
                  </button>
                  <button className="packet-primary-btn" onClick={confirmAction} disabled={busy}>
                    <span className="material-symbols-rounded">check</span>
                    {busy ? 'Saving...' : 'Yes'}
                  </button>
                </div>
              </div>
            )}
            {!action && (
              <button className="packet-primary-btn slim" onClick={resetScan} disabled={busy}>
                <span className="material-symbols-rounded">qr_code_scanner</span>
                Scan Next Packet
              </button>
            )}
          </div>
        )}
      </div>
    </section>
  );
}

function PrintPanel() {
  const [printTab, setPrintTab] = useStatePacket('base');
  const [selectedSkuId, setSelectedSkuId] = useStatePacket(SKU_CATALOG[0].skuId);
  const [selectedPacketId, setSelectedPacketId] = useStatePacket('');
  const [eligiblePackets, setEligiblePackets] = useStatePacket([]);
  const [previewPacket, setPreviewPacket] = useStatePacket(null);
  const [busy, setBusy] = useStatePacket(false);
  const [message, setMessage] = useStatePacket({ type: '', text: '' });

  const selectedSku = useMemoPacket(() => SKU_BY_ID[selectedSkuId], [selectedSkuId]);
  const selectedParent = useMemoPacket(
    () => eligiblePackets.find((p) => p.uniquePacketId === selectedPacketId),
    [eligiblePackets, selectedPacketId]
  );

  const loadEligible = async (silent) => {
    setBusy(true);
    if (!silent) setMessage({ type: '', text: '' });
    try {
      const packets = await listPacketsEligibleForMarinatedMrd();
      setEligiblePackets(packets);
      setSelectedPacketId(packets[0]?.uniquePacketId || '');
      if (!silent && !packets.length) setMessage({ type: 'info', text: 'No packets are currently eligible for marinated QR/MRD printing.' });
    } catch (err) {
      setMessage({ type: 'error', text: err.message || 'Unable to load eligible packets.' });
    } finally {
      setBusy(false);
    }
  };

  useEffectPacket(() => {
    if (printTab === 'marinated') loadEligible();
  }, [printTab]);

  const triggerPrint = () => {
    window.setTimeout(() => window.print(), 350);
  };

  const printBase = async () => {
    if (!selectedSku || busy) return;
    if (!selectedSku.canPrintBaseMRD) {
      setMessage({ type: 'error', text: 'This SKU is not enabled for base MRD printing.' });
      return;
    }
    setBusy(true);
    setMessage({ type: '', text: '' });
    try {
      const record = await createPacketRecord(selectedSku);
      setPreviewPacket(record);
      setMessage({ type: 'success', text: 'Base packet QR/MRD created in Firebase. Print dialog is opening.' });
      triggerPrint();
    } catch (err) {
      setMessage({ type: 'error', text: err.message || 'Firebase write failed.' });
    } finally {
      setBusy(false);
    }
  };

  const printMarinated = async () => {
    if (!selectedParent || busy) return;
    setBusy(true);
    setMessage({ type: '', text: '' });
    try {
      const record = await createMarinatedMrdRecord(selectedParent);
      setPreviewPacket(record);
      setMessage({ type: 'success', text: 'Marinated QR/MRD created in Firebase. Print dialog is opening.' });
      await loadEligible(true);
      triggerPrint();
    } catch (err) {
      setMessage({ type: 'error', text: err.message || 'Firebase write failed.' });
    } finally {
      setBusy(false);
    }
  };

  return (
    <section className="packet-workspace print-grid">
      <div className="packet-panel print-control-panel">
        <div className="packet-tabs">
          <button className={printTab === 'base' ? 'active' : ''} onClick={() => setPrintTab('base')}>
            <span className="material-symbols-rounded">inventory_2</span>
            Standard SKU Packet
          </button>
          <button className={printTab === 'marinated' ? 'active' : ''} onClick={() => setPrintTab('marinated')}>
            <span className="material-symbols-rounded">cyclone</span>
            Print Marinated QR/MRD
          </button>
        </div>

        {printTab === 'base' && (
          <>
            <div className="packet-section-title">
              <h2>Select SKU</h2>
              <p>Packet size is fixed by SKU and cannot be edited by staff.</p>
            </div>
            <div className="sku-grid">
              {SKU_CATALOG.map((sku) => (
                <button
                  key={sku.skuId}
                  className={`sku-card ${selectedSkuId === sku.skuId ? 'selected' : ''}`}
                  onClick={() => setSelectedSkuId(sku.skuId)}
                  disabled={!sku.canPrintBaseMRD}
                >
                  <strong>{sku.displayName}</strong>
                  <span>{sku.defaultPacketSize}</span>
                  <small>{sku.shelfLifeDays} days / {sku.shelfLifeHours} hours shelf life</small>
                </button>
              ))}
            </div>
            <button className="packet-primary-btn tall" onClick={printBase} disabled={busy || !selectedSku}>
              <span className="material-symbols-rounded">print</span>
              {busy ? 'Creating Sticker...' : 'Print QR MRD Sticker'}
            </button>
          </>
        )}

        {printTab === 'marinated' && (
          <>
            <div className="packet-section-title">
              <h2>Eligible In-Marination Packets</h2>
              <p>Only packets scanned out of inventory to marination appear here.</p>
            </div>
            <div className="eligible-list">
              {eligiblePackets.map((packet) => (
                <button
                  key={packet.uniquePacketId}
                  className={`eligible-card ${selectedPacketId === packet.uniquePacketId ? 'selected' : ''}`}
                  onClick={() => setSelectedPacketId(packet.uniquePacketId)}
                >
                  <div>
                    <strong>{packet.skuName}</strong>
                    <span>{packet.uniquePacketId}</span>
                  </div>
                  <StatusPill status={packet.status} />
                </button>
              ))}
              {!eligiblePackets.length && (
                <div className="empty-state">
                  <span className="material-symbols-rounded">inventory_2</span>
                  <strong>No eligible packets</strong>
                  <p>Scan an in-inventory packet out to marination first.</p>
                </div>
              )}
            </div>
            <button className="packet-primary-btn tall" onClick={printMarinated} disabled={busy || !selectedParent}>
              <span className="material-symbols-rounded">print</span>
              {busy ? 'Creating Marinated Label...' : 'Print Marinated QR/MRD'}
            </button>
          </>
        )}

        {message.text && <div className={`packet-alert ${message.type}`}>{message.text}</div>}
      </div>

      <div className="packet-panel preview-panel">
        <div className="packet-panel-head">
          <span className="material-symbols-rounded">receipt_long</span>
          <div>
            <h2>Print Sticker Preview</h2>
            <p>QR stores only the packet ID and resolves details from Firebase.</p>
          </div>
        </div>
        {previewPacket ? (
          <PacketSticker packet={previewPacket} />
        ) : (
          <div className="preview-placeholder">
            <span className="material-symbols-rounded">qr_code_2</span>
            <strong>No sticker generated yet</strong>
            <p>Select a SKU or eligible marination packet, then print.</p>
          </div>
        )}
      </div>
    </section>
  );
}

function PacketQrMrdScreen({ onBack }) {
  const [mode, setMode] = useStatePacket(null);
  const stats = [
    { v: SKU_CATALOG.length, l: 'SKUS' },
    { v: '48h', l: 'DEFAULT LIFE' },
    { v: 'LIVE', l: 'FIREBASE' },
  ];

  return (
    <div className="view view-enter">
      <SubHead
        onBack={mode ? () => setMode(null) : onBack}
        en="Packet QR / MRD Management"
        hi="Packet QR / MRD"
        stats={stats}
      />
      <div className="packet-page">
        <ModeCards mode={mode} onMode={setMode} />
        {!mode && (
          <div className="packet-welcome">
            <div className="packet-welcome-card">
              <span className="material-symbols-rounded">verified</span>
              <div>
                <h2>Choose an operation</h2>
                <p>Use Scanner for inventory movement. Use QR-MRD Print for standard packet labels and marinated MRD labels.</p>
              </div>
            </div>
          </div>
        )}
        {mode === 'scanner' && <ScannerPanel />}
        {mode === 'print' && <PrintPanel />}
      </div>
    </div>
  );
}

function PacketStandaloneApp() {
  const [showBroadcast, setShowBroadcast] = useStatePacket(true);
  const goHome = () => {
    window.location.href = './KFC Kitchen OS.html';
  };
  return (
    <div className="screen" data-brand="classic" data-density="standard" data-lang="english" data-screen-label="KFC ArDh - Packet QR MRD">
      <TopBar
        deviceCount={9}
        onlineCount={8}
        alerts={3}
        lowStock={6}
        onHome={goHome}
        onDevices={goHome}
        onAlerts={goHome}
        onTweaks={() => {}}
      />
      {showBroadcast && (
        <div className="broadcast packet-broadcast">
          <div className="icon-tag"><span className="material-symbols-rounded" style={{ fontSize: 18 }}>qr_code</span></div>
          <div className="marquee"><span>Packet QR / MRD operations write to Firebase packets and inventoryEvents.</span></div>
          <button className="dismiss" onClick={() => setShowBroadcast(false)}>
            <span className="material-symbols-rounded" style={{ fontSize: 18 }}>close</span>
          </button>
        </div>
      )}
      <div className="content">
        <PacketQrMrdScreen onBack={goHome} />
      </div>
    </div>
  );
}

Object.assign(window, {
  PacketQrMrdScreen,
  PacketStandaloneApp,
  PACKET_STATUS,
  SKU_CATALOG,
});
