/* global React, IntakeIcon, IntakeStatusBar, IntakeTopBar, IntakeStepDots, IntakeAvatar, IntakeFakeQR, intakeGradientFor,
          INTAKE_PRODUCERS, INTAKE_DAILY_PRICES, INTAKE_PAYMENT_METHODS, INTAKE_TODAY, INTAKE_STATUS,
          intakeFmtCOP, intakeFmtKG, intakeFmtUSD, intakeFmtInt */

// ───── Annona Intake — Screens 1-5 ─────

const Icon = IntakeIcon;

// ═══════════════════════════════════════════════════════════════
// SCREEN 1 — HOME / TODAY
// ═══════════════════════════════════════════════════════════════
function ScreenHome() {
  const totals = INTAKE_TODAY.reduce((a, x) => ({ bags: a.bags + x.bags, kg: a.kg + x.kg, cop: a.cop + x.value_cop }), { bags: 0, kg: 0, cop: 0 });
  return (
    <div className="intake-screen intake-root">
      <IntakeStatusBar sync="online" />
      <div className="topbar" style={{ borderBottom: 'none', paddingTop: 14 }}>
        <IntakeAvatar initials="WB" size="md" color="linear-gradient(135deg,#2B1D10,#5A4634)" />
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 12, color: 'var(--ink-3)', fontWeight: 500 }}>Lunes, 23 abr</div>
          <div style={{ fontSize: 16, fontWeight: 600 }}>Walter Buizer</div>
        </div>
        <div style={{ width: 40, height: 40, borderRadius: 12, background: 'var(--paper-dim)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Icon name="sync" size={20} />
        </div>
      </div>

      <div className="scroll" style={{ padding: '8px 16px 100px' }}>
        {/* Daily price hero */}
        <div className="intake-card" style={{ padding: 20, background: 'linear-gradient(135deg,#2B1D10 0%,#3F2B18 100%)', color: '#FBF7F0', position: 'relative', overflow: 'hidden' }}>
          <div style={{ position: 'absolute', top: -40, right: -30, width: 180, height: 180, borderRadius: '50%', background: 'radial-gradient(circle, rgba(184,137,75,0.35), transparent 60%)' }} />
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, fontWeight: 500, color: 'var(--gold-dim)', letterSpacing: '0.06em', textTransform: 'uppercase' }}>
            <Icon name="coins" size={14} /> Precio del día · Huila
          </div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginTop: 8 }}>
            <span className="f-display" style={{ fontSize: 40, letterSpacing: '-0.02em' }}>$14.850</span>
            <span style={{ fontSize: 14, color: 'var(--gold-dim)' }}>COP / kg pergamino</span>
          </div>
          <div style={{ display: 'flex', gap: 16, marginTop: 14, fontSize: 12, color: 'rgba(251,247,240,0.7)' }}>
            <div>C-market <b style={{ color: '#FBF7F0' }}>$3,47</b></div>
            <div>Dif. <b style={{ color: '#FBF7F0' }}>+$0,42</b></div>
            <div>FX <b style={{ color: '#FBF7F0' }}>4.120</b></div>
          </div>
          <div style={{ marginTop: 10, fontSize: 11, color: 'rgba(251,247,240,0.5)' }}>Fijado 05:42 · Bogotá · vigente hoy</div>
        </div>

        {/* Big CTA */}
        <button className="btn-primary gold" style={{ marginTop: 16, height: 84, fontSize: 19, borderRadius: 22, boxShadow: '0 8px 24px rgba(184,137,75,0.35)' }}>
          <Icon name="qr" size={26} /> Nueva entrega
        </button>

        {/* Today's stats */}
        <div style={{ marginTop: 22, display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
          <div className="f-display" style={{ fontSize: 22 }}>Hoy</div>
          <div style={{ fontSize: 13, color: 'var(--ink-3)' }}>{INTAKE_TODAY.length} entregas</div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8, marginTop: 10 }}>
          <div className="metric" style={{ padding: 12 }}>
            <div className="label">Sacos</div>
            <div className="value f-num">{totals.bags}</div>
          </div>
          <div className="metric" style={{ padding: 12 }}>
            <div className="label">Peso</div>
            <div className="value f-num">{(totals.kg / 1000).toFixed(1).replace('.', ',')}<span style={{ fontSize: 14, color: 'var(--ink-3)', marginLeft: 3 }}>t</span></div>
          </div>
          <div className="metric" style={{ padding: 12 }}>
            <div className="label">Valor</div>
            <div className="value f-num" style={{ fontSize: 20 }}>{(totals.cop / 1_000_000).toFixed(1).replace('.', ',')}<span style={{ fontSize: 13, color: 'var(--ink-3)', marginLeft: 3 }}>M</span></div>
          </div>
        </div>

        {/* Recent intakes */}
        <div style={{ marginTop: 20, fontSize: 12, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600 }}>Últimas entregas</div>
        <div className="intake-card" style={{ marginTop: 8 }}>
          {INTAKE_TODAY.slice(0, 3).map(it => {
            const s = INTAKE_STATUS[it.status];
            return (
              <div key={it.id} className="intake-row">
                <IntakeAvatar initials={it.initials} color={intakeGradientFor(it.id)} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontWeight: 600, fontSize: 15, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{it.producer}</div>
                  <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 2 }}>{it.time} · {it.bags} sacos · {intakeFmtKG(it.kg)}</div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <div style={{ fontWeight: 600, fontSize: 14 }} className="f-num">{intakeFmtCOP(it.value_cop)}</div>
                  <span className={'chip ' + s.cls} style={{ marginTop: 4, height: 22, fontSize: 11 }}>{s.label}</span>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════
// SCREEN 2 — IDENTIFY PRODUCER (QR scan + GPS nearby)
// ═══════════════════════════════════════════════════════════════
function ScreenIdentify() {
  return (
    <div className="intake-screen intake-root">
      <IntakeStatusBar sync="online" />
      <IntakeTopBar title="Identificar productor" subtitle="Paso 1 de 4" onBack right={<IntakeStepDots step={0} total={4} />} />

      <div className="scroll" style={{ padding: '16px 16px 100px' }}>
        {/* Scanner viewfinder */}
        <div className="viewfinder">
          {/* corners */}
          <div className="corner" style={{ top: 32, left: 32, borderTop: '3px solid var(--gold)', borderLeft: '3px solid var(--gold)', borderTopLeftRadius: 14 }} />
          <div className="corner" style={{ top: 32, right: 32, borderTop: '3px solid var(--gold)', borderRight: '3px solid var(--gold)', borderTopRightRadius: 14 }} />
          <div className="corner" style={{ bottom: 32, left: 32, borderBottom: '3px solid var(--gold)', borderLeft: '3px solid var(--gold)', borderBottomLeftRadius: 14 }} />
          <div className="corner" style={{ bottom: 32, right: 32, borderBottom: '3px solid var(--gold)', borderRight: '3px solid var(--gold)', borderBottomRightRadius: 14 }} />
          <div className="scan-bar" />
          <div style={{ position: 'absolute', bottom: 16, left: 0, right: 0, textAlign: 'center', color: 'rgba(255,255,255,0.8)', fontSize: 13, fontWeight: 500, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}>
            <Icon name="scan" size={16} color="#fff" /> Buscando código QR del productor…
          </div>
          <div style={{ position: 'absolute', top: 16, left: 16, padding: '4px 10px', borderRadius: 999, background: 'rgba(0,0,0,0.5)', color: '#fff', fontSize: 11, fontWeight: 500, display: 'flex', alignItems: 'center', gap: 6 }}>
            <span style={{ width: 6, height: 6, borderRadius: '50%', background: '#4ADE80' }} /> Lector Bluetooth conectado
          </div>
        </div>

        {/* GPS nearby */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 22, fontSize: 12, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600 }}>
          <Icon name="mapPin" size={14} /> Productores cerca · Bruselas
        </div>
        <div className="intake-card" style={{ marginTop: 8 }}>
          {INTAKE_PRODUCERS.map(p => (
            <div key={p.id} className="intake-row">
              <IntakeAvatar initials={p.initials} color={intakeGradientFor(p.id)} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontWeight: 600, fontSize: 15 }}>{p.name}</div>
                <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 2 }}>{p.village} · {p.plots} plots</div>
              </div>
              <div style={{ textAlign: 'right', fontSize: 12, color: 'var(--ink-3)' }}>
                <div style={{ fontWeight: 600, color: 'var(--ink-2)' }} className="f-num">{p.distance} m</div>
                <div>{p.id}</div>
              </div>
            </div>
          ))}
        </div>

        <button className="btn-secondary" style={{ marginTop: 12 }}>
          <Icon name="plus" size={18} /> Registrar productor nuevo
        </button>
      </div>

      <div className="shelf">
        <button className="btn-secondary">
          <Icon name="search" size={18} /> Buscar por nombre o cédula
        </button>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════
// SCREEN 3 — PLOT SELECTION
// ═══════════════════════════════════════════════════════════════
function ScreenPlot() {
  const p = INTAKE_PRODUCERS[0];
  return (
    <div className="intake-screen intake-root">
      <IntakeStatusBar sync="online" />
      <IntakeTopBar title="Elegir plot" subtitle="Paso 2 de 4" onBack right={<IntakeStepDots step={1} total={4} />} />

      <div className="scroll" style={{ padding: '12px 16px 100px' }}>
        {/* Producer card */}
        <div className="intake-card" style={{ padding: 18, display: 'flex', gap: 14, alignItems: 'center' }}>
          <IntakeAvatar initials={p.initials} size="lg" color={intakeGradientFor(p.id)} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 11, color: 'var(--ink-3)', fontWeight: 500, letterSpacing: '0.05em', textTransform: 'uppercase' }}>{p.id} · escaneado</div>
            <div className="f-display" style={{ fontSize: 22, marginTop: 2, letterSpacing: '-0.01em' }}>{p.name}</div>
            <div style={{ fontSize: 13, color: 'var(--ink-2)', marginTop: 4 }}>{p.cooperative} · {p.village}</div>
          </div>
          <div style={{ width: 36, height: 36, borderRadius: '50%', background: 'var(--green-soft)', color: 'var(--green)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon name="check" size={22} />
          </div>
        </div>

        <div style={{ marginTop: 20, fontSize: 12, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600 }}>
          ¿De qué plot viene este café?
        </div>
        <div style={{ marginTop: 4, fontSize: 13, color: 'var(--ink-2)' }}>
          Obligatorio para EUDR. Si es mezcla de plots, selecciona varios.
        </div>

        <div style={{ marginTop: 12, display: 'flex', flexDirection: 'column', gap: 10 }}>
          {p.plotList.map((plot, i) => (
            <div key={plot.id} className="intake-card" style={{ padding: 14, display: 'flex', gap: 14, alignItems: 'center', border: i === 0 ? '2px solid var(--gold)' : '2px solid transparent' }}>
              <div className="plot-thumb" style={{ width: 64, height: 64 }} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontWeight: 600, fontSize: 16 }}>{plot.name}</div>
                <div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 2 }}>{plot.var}</div>
                <div style={{ display: 'flex', gap: 10, marginTop: 6, fontSize: 12 }}>
                  <span className="chip outline" style={{ height: 22, fontSize: 11 }}>{plot.ha} ha</span>
                  <span className="chip outline" style={{ height: 22, fontSize: 11 }}>{plot.alt}</span>
                  <span className="chip outline" style={{ height: 22, fontSize: 11 }}>pick {plot.lastPick}</span>
                </div>
              </div>
              <div style={{ width: 24, height: 24, borderRadius: '50%', border: '2px solid ' + (i === 0 ? 'var(--gold)' : 'var(--ink-line)'), background: i === 0 ? 'var(--gold)' : 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                {i === 0 && <Icon name="check" size={14} color="#2B1D10" stroke={3} />}
              </div>
            </div>
          ))}
        </div>
      </div>

      <div className="shelf">
        <button className="btn-primary">Continuar con La Esperanza <Icon name="chev" size={20} color="#FBF7F0" /></button>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════
// SCREEN 4 — WEIGHING (Wizard variant — one bag at a time)
// ═══════════════════════════════════════════════════════════════
function ScreenWeighWizard() {
  return (
    <div className="intake-screen intake-root">
      <IntakeStatusBar sync="online" />
      <IntakeTopBar title="Pesar saco" subtitle="Saco 4 de ~8" onBack right={<IntakeStepDots step={2} total={4} />} />

      <div className="scroll" style={{ padding: '16px 16px 100px' }}>
        {/* Current scanned bag */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 12px', background: 'var(--gold-soft)', borderRadius: 14, color: 'var(--ink)', fontSize: 13, fontWeight: 500 }}>
          <span style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--gold)' }} />
          QR leído · <span className="f-num" style={{ fontWeight: 600 }}>BAG-0214-0041</span>
        </div>

        {/* Big weight display */}
        <div style={{ marginTop: 24, textAlign: 'center' }}>
          <div style={{ fontSize: 12, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600 }}>Peso del saco</div>
          <div style={{ marginTop: 10, fontFamily: 'Fraunces, serif', fontSize: 88, fontWeight: 500, lineHeight: 1, letterSpacing: '-0.03em', color: 'var(--ink)' }} className="f-num">
            64<span style={{ fontSize: 52, color: 'var(--ink-3)' }}>,8</span>
          </div>
          <div style={{ fontSize: 18, color: 'var(--ink-3)', marginTop: 4 }}>kilogramos</div>
        </div>

        {/* Keypad */}
        <div style={{ marginTop: 22, display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8 }}>
          {['1','2','3','4','5','6','7','8','9',',','0','⌫'].map(k => (
            <div key={k} style={{ height: 64, borderRadius: 16, background: 'var(--card)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 24, fontWeight: 500, color: 'var(--ink)', boxShadow: 'var(--card-shadow)' }} className="f-num">
              {k}
            </div>
          ))}
        </div>

        {/* Running total */}
        <div className="intake-card" style={{ marginTop: 18, padding: 14, display: 'flex', alignItems: 'center', gap: 12 }}>
          <Icon name="bag" size={22} color="var(--ink-2)" />
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 12, color: 'var(--ink-3)', fontWeight: 500 }}>Total acumulado · 3 sacos</div>
            <div style={{ fontSize: 18, fontWeight: 600 }} className="f-num">192,4 kg</div>
          </div>
          <div style={{ fontSize: 12, color: 'var(--ink-3)', textAlign: 'right' }}>
            <div>Valor</div>
            <div style={{ fontWeight: 600, color: 'var(--ink)' }} className="f-num">$ 2.857.140</div>
          </div>
        </div>
      </div>

      <div className="shelf">
        <button className="btn-primary">
          <Icon name="check" size={22} color="#FBF7F0" /> Guardar saco · escanear siguiente
        </button>
        <button className="btn-secondary">Terminar y continuar a precio</button>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════
// SCREEN 5 — WEIGHING (Single-screen variant — all bags listed)
// ═══════════════════════════════════════════════════════════════
function ScreenWeighSingle() {
  const bags = [
    { id: 'BAG-0214-0038', kg: 62.4 },
    { id: 'BAG-0214-0039', kg: 64.1 },
    { id: 'BAG-0214-0040', kg: 65.9 },
    { id: 'BAG-0214-0041', kg: 64.8 },
    { id: 'BAG-0214-0042', kg: 63.2, active: true },
  ];
  const total = bags.reduce((a, b) => a + b.kg, 0);
  return (
    <div className="intake-screen intake-root">
      <IntakeStatusBar sync="online" />
      <IntakeTopBar title="Sacos · La Esperanza" subtitle="Paso 3 de 4" onBack right={<IntakeStepDots step={2} total={4} />} />

      <div className="scroll" style={{ padding: '12px 0 100px' }}>
        {/* Total hero */}
        <div style={{ padding: '0 16px' }}>
          <div className="intake-card" style={{ padding: 18, background: 'linear-gradient(135deg, var(--gold-soft), #FBF7F0)', border: '1px solid var(--gold-dim)' }}>
            <div style={{ fontSize: 11, color: 'var(--gold)', fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase' }}>Total de la entrega</div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginTop: 4 }}>
              <span className="f-display" style={{ fontSize: 40, letterSpacing: '-0.02em' }} >{total.toFixed(1).replace('.', ',')}</span>
              <span style={{ fontSize: 16, color: 'var(--ink-2)' }}>kg · {bags.length} sacos</span>
            </div>
            <div style={{ marginTop: 6, fontSize: 13, color: 'var(--ink-2)' }} className="f-num">≈ $ {Math.round(total * 14850).toLocaleString('es-CO').replace(/,/g, '.')} COP</div>
          </div>
        </div>

        {/* Bag list */}
        <div style={{ marginTop: 18, padding: '0 16px', fontSize: 12, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600, display: 'flex', justifyContent: 'space-between' }}>
          <span>Sacos</span>
          <span>Peso · kg</span>
        </div>

        <div style={{ padding: '0 16px', marginTop: 8 }}>
          <div className="intake-card">
            {bags.map((b, i) => (
              <div key={b.id} className="intake-row" style={{ padding: '12px 14px', minHeight: 56 }}>
                <div style={{ width: 32, height: 32, borderRadius: 10, background: b.active ? 'var(--gold)' : 'var(--paper-dim)', color: b.active ? '#2B1D10' : 'var(--ink-2)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 600, fontSize: 14 }} className="f-num">{i + 1}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 500 }} className="f-num">{b.id}</div>
                  {b.active && <div style={{ fontSize: 11, color: 'var(--gold)', fontWeight: 500, marginTop: 1 }}>Pesando ahora…</div>}
                </div>
                <div style={{ fontSize: 18, fontWeight: 600, textAlign: 'right' }} className="f-num">{b.kg.toFixed(1).replace('.', ',')}</div>
              </div>
            ))}
            {/* Add row */}
            <div style={{ padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 10, color: 'var(--ink-2)', fontWeight: 500, background: 'var(--paper-dim)' }}>
              <div style={{ width: 32, height: 32, borderRadius: 10, background: 'var(--card)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <Icon name="scan" size={18} />
              </div>
              <div style={{ flex: 1, fontSize: 14 }}>Escanear siguiente saco…</div>
              <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>Bluetooth</div>
            </div>
          </div>
        </div>

        {/* Offline hint */}
        <div style={{ padding: '0 16px', marginTop: 14, display: 'flex', alignItems: 'center', gap: 8, fontSize: 12, color: 'var(--ink-3)' }}>
          <Icon name="cloud" size={14} /> Guardado localmente · se sincroniza al tener señal
        </div>
      </div>

      <div className="shelf">
        <button className="btn-primary">Terminar · ir a precio <Icon name="chev" size={20} color="#FBF7F0" /></button>
      </div>
    </div>
  );
}

Object.assign(window, {
  IntakeScreenHome: ScreenHome,
  IntakeScreenIdentify: ScreenIdentify,
  IntakeScreenPlot: ScreenPlot,
  IntakeScreenWeighWizard: ScreenWeighWizard,
  IntakeScreenWeighSingle: ScreenWeighSingle,
});
