/* ============================================================
   Zavod quvvati (factory capacity) — jonli dashboard
   Har bir qator platformadagi mahsulotga bog'langan; summa = karobka × mahsulot narxi.
   Narx o'zgarsa — summalar avtomatik o'zgaradi (DB.PRODUCT_BY_ID dan jonli o'qiydi).
   Oylik (Iyul–Dekabr) + haftalik (1–4 hafta) ko'rinish.
   sdShort/sdFull/SdKpi helperlari sheetdash.jsx dan qayta ishlatiladi.
   ============================================================ */

// Zavod oylari — fayl Iyul(7)..Dekabr(12) bo'yicha
const FACTORY_MONTHS = [
  { n: 7, label: 'Iyul' },
  { n: 8, label: 'Avgust' },
  { n: 9, label: 'Sentyabr' },
  { n: 10, label: 'Oktyabr' },
  { n: 11, label: 'Noyabr' },
  { n: 12, label: 'Dekabr' },
];

// Bitta qatorning bir oydagi haftalik massivini xavfsiz o'qish (har doim 4 hafta)
function fcWeeks(row, monthN) {
  const arr = (row && row.months && row.months[String(monthN)]) || [];
  const out = [0, 0, 0, 0];
  for (let i = 0; i < 4; i++) out[i] = Number(arr[i] || 0);
  return out;
}
function fcMonthQty(row, monthN) {
  return fcWeeks(row, monthN).reduce((s, v) => s + v, 0);
}
// Pozitsiyaga biriktirilgan mahsulotlar (bir nechta bo'lishi mumkin)
function fcProducts(row) {
  const ids = (row && row.productIds && row.productIds.length) ? row.productIds : (row && row.productId ? [row.productId] : []);
  return ids.map((id) => DB.PRODUCT_BY_ID[id]).filter(Boolean);
}
// Mahsulot narxi (jonli) — bir nechta bo'lsa o'rtacha narx, bog'lanmagan bo'lsa 0
function fcPrice(row) {
  const prices = fcProducts(row).map((p) => Number(p.price || 0));
  if (!prices.length) return 0;
  return prices.reduce((a, b) => a + b, 0) / prices.length;
}

// Oylik ishlab chiqarish grafigi (karobka yoki summa) — barcha oylar bo'ylab
function FcMonthBars({ rows, metric }) {
  const data = FACTORY_MONTHS.map((m) => {
    let total = 0;
    rows.forEach((r) => {
      const q = fcMonthQty(r, m.n);
      total += metric === 'summa' ? q * fcPrice(r) : q;
    });
    return { label: m.label, total };
  });
  const max = Math.max(1, ...data.map((d) => d.total));
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', gap: 12, height: 180, paddingTop: 8 }}>
      {data.map((d, i) => {
        const h = Math.max(2, (d.total / max) * 100);
        return (
          <div key={i} style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, height: '100%', justifyContent: 'flex-end' }}>
            <div className="tnum" style={{ fontSize: 9.5, fontWeight: 600, color: 'var(--ink-4)', whiteSpace: 'nowrap' }}>{sdShort(d.total)}</div>
            <div title={d.label + ': ' + sdFull(d.total)} style={{
              width: '100%', maxWidth: 46, height: h + '%', borderRadius: '6px 6px 0 0',
              background: 'linear-gradient(180deg,var(--brand),var(--brand-700))', transition: 'height .4s var(--ease)',
            }} />
            <div style={{ fontSize: 10.5, fontWeight: 600, color: 'var(--ink-3)' }}>{d.label}</div>
          </div>
        );
      })}
    </div>
  );
}

function FactoryView() {
  const [monthN, setMonthN] = useState(FACTORY_MONTHS[0].n);
  const [metric, setMetric] = useState('karobka'); // 'karobka' | 'summa'
  const rows = DB.FACTORY_CAPACITY || [];

  if (!rows.length) {
    return (
      <div style={{ height: '100%', display: 'grid', placeItems: 'center', padding: 24 }}>
        <div style={{ maxWidth: 440, textAlign: 'center', display: 'flex', flexDirection: 'column', gap: 12, color: 'var(--ink-3)' }}>
          <div style={{ display: 'grid', placeItems: 'center' }}><Icon name="box" size={26} /></div>
          <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--ink)' }}>Zavod quvvati kiritilmagan</div>
          <div style={{ fontSize: 13 }}>Sozlamalar → Zavod quvvati bo'limidan qatorlar qo'shing yoki namunaviy jadvalni yuklang.</div>
        </div>
      </div>
    );
  }

  // Tanlangan oy bo'yicha hisob
  const monthRows = rows.map((r) => {
    const weeks = fcWeeks(r, monthN);
    const qty = weeks.reduce((s, v) => s + v, 0);
    const price = fcPrice(r);
    const products = fcProducts(r);
    const product = products[0] || null;
    const productLabel = products.length ? products.map((p) => p.name).join(', ') : '';
    return { row: r, weeks, qty, price, summa: qty * price, product, products, productLabel };
  });
  const totalQty = monthRows.reduce((s, x) => s + x.qty, 0);
  const totalSumma = monthRows.reduce((s, x) => s + x.summa, 0);
  const linked = monthRows.filter((x) => x.product).length;

  // Yarim yillik jami (barcha oylar)
  const grandQty = rows.reduce((s, r) => s + FACTORY_MONTHS.reduce((a, m) => a + fcMonthQty(r, m.n), 0), 0);
  const grandSumma = rows.reduce((s, r) => s + FACTORY_MONTHS.reduce((a, m) => a + fcMonthQty(r, m.n), 0) * fcPrice(r), 0);

  const mLabel = (FACTORY_MONTHS.find((m) => m.n === monthN) || {}).label || '';

  return (
    <div className="dash-wrap" style={{ padding: '8px 28px 32px', overflowY: 'auto', height: '100%' }}>
      {/* Sarlavha */}
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 14, flexWrap: 'wrap', margin: '8px 0 16px' }}>
        <div>
          <h2 style={{ fontSize: 22, fontWeight: 700, letterSpacing: '-.02em', margin: 0 }}>Zavod quvvati</h2>
          <p style={{ fontSize: 12.5, margin: '4px 0 0', color: 'var(--ink-4)' }}>
            O'lchov birligi — karobka · Summa = karobka × mahsulot narxi (jonli) · {rows.length} pozitsiya
          </p>
        </div>
        {/* Oylar tugmalari */}
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
          {FACTORY_MONTHS.map((m) => (
            <button key={m.n} className={'btn ' + (m.n === monthN ? 'btn--primary' : 'btn--ghost')} onClick={() => setMonthN(m.n)} style={{ padding: '6px 12px', fontSize: 12.5 }}>
              {m.label}
            </button>
          ))}
        </div>
      </div>

      {/* KPI kartalar */}
      <div className="dash-cards" style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 18 }}>
        <SdKpi label={mLabel + ' — jami quvvat'} value={sdShort(totalQty)} sub={sdFull(totalQty) + ' karobka'} big />
        <SdKpi label={mLabel + ' — jami summa'} value={sdShort(totalSumma)} sub={sdFull(totalSumma) + ' soʼm'} accent="var(--brand-700)" big />
        <SdKpi label="Yarim yillik quvvat" value={sdShort(grandQty)} sub={'Iyul–Dekabr · ' + sdFull(grandQty) + ' karobka'} big />
        <SdKpi label="Yarim yillik summa" value={sdShort(grandSumma)} sub={sdFull(grandSumma) + ' soʼm'} accent="var(--brand-700)" big />
      </div>

      {linked < rows.length && (
        <div style={{ marginBottom: 14, fontSize: 12, color: '#A6651E', background: 'rgba(227,162,59,.12)', border: '1px solid rgba(227,162,59,.3)', borderRadius: 'var(--r-md)', padding: '8px 12px' }}>
          {rows.length - linked} ta pozitsiya mahsulotga bog'lanmagan — ularning summasi 0. Sozlamalar → Zavod quvvati bo'limidan mahsulotni biriktiring.
        </div>
      )}

      {/* Oy bo'yicha jadval: haftalar + oylik jami + summa */}
      <div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', boxShadow: 'var(--sh-1)', overflow: 'hidden', marginBottom: 18 }}>
        <div style={{ padding: '14px 20px 10px', fontSize: 13, fontWeight: 700 }}>{mLabel} — haftalik ishlab chiqarish</div>
        <div style={{ overflowX: 'auto' }}>
          <table className="sd-table" style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12.5, minWidth: 720 }}>
            <thead>
              <tr style={{ textAlign: 'right', color: 'var(--ink-4)', fontSize: 11, textTransform: 'uppercase', letterSpacing: '.03em' }}>
                <th style={{ textAlign: 'left', padding: '8px 20px', fontWeight: 600 }}>Pozitsiya</th>
                <th style={{ padding: '8px 10px', fontWeight: 600 }}>1-hafta</th>
                <th style={{ padding: '8px 10px', fontWeight: 600 }}>2-hafta</th>
                <th style={{ padding: '8px 10px', fontWeight: 600 }}>3-hafta</th>
                <th style={{ padding: '8px 10px', fontWeight: 600 }}>4-hafta</th>
                <th style={{ padding: '8px 12px', fontWeight: 600 }}>Oylik (karobka)</th>
                <th style={{ padding: '8px 12px', fontWeight: 600 }}>Narx</th>
                <th style={{ padding: '8px 20px', fontWeight: 600 }}>Summa</th>
              </tr>
            </thead>
            <tbody>
              {monthRows.map((x, i) => (
                <tr key={i} style={{ borderTop: '1px solid var(--border)' }}>
                  <td style={{ textAlign: 'left', padding: '9px 20px', fontWeight: 600 }}>
                    {x.row.name}
                    <div style={{ fontSize: 11, fontWeight: 500, color: x.product ? 'var(--ink-4)' : '#C2453A' }}>
                      {x.productLabel || 'Mahsulot biriktirilmagan'}{x.products && x.products.length > 1 ? ' · o\'rtacha narx' : ''}
                    </div>
                  </td>
                  {x.weeks.map((w, wi) => (
                    <td key={wi} className="tnum" style={{ textAlign: 'right', padding: '9px 10px', color: 'var(--ink-3)' }}>{sdFull(w)}</td>
                  ))}
                  <td className="tnum" style={{ textAlign: 'right', padding: '9px 12px', fontWeight: 700 }}>{sdFull(x.qty)}</td>
                  <td className="tnum" style={{ textAlign: 'right', padding: '9px 12px', color: 'var(--ink-3)' }}>{x.price ? sdFull(x.price) : '—'}</td>
                  <td className="tnum" style={{ textAlign: 'right', padding: '9px 20px', fontWeight: 700, color: 'var(--brand-700)' }}>{x.summa ? sdFull(x.summa) : '—'}</td>
                </tr>
              ))}
            </tbody>
            <tfoot>
              <tr style={{ borderTop: '2px solid var(--border)', background: 'var(--bg-soft, rgba(127,127,127,.05))' }}>
                <td style={{ textAlign: 'left', padding: '10px 20px', fontWeight: 700 }}>Jami</td>
                <td colSpan={4}></td>
                <td className="tnum" style={{ textAlign: 'right', padding: '10px 12px', fontWeight: 700 }}>{sdFull(totalQty)}</td>
                <td></td>
                <td className="tnum" style={{ textAlign: 'right', padding: '10px 20px', fontWeight: 700, color: 'var(--brand-700)' }}>{sdFull(totalSumma)}</td>
              </tr>
            </tfoot>
          </table>
        </div>
      </div>

      {/* Oylik grafik (Iyul–Dekabr) */}
      <div style={{ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 'var(--r-lg)', padding: '16px 20px 12px', boxShadow: 'var(--sh-1)' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 8, marginBottom: 8 }}>
          <div style={{ fontSize: 13, fontWeight: 700 }}>Oylik ishlab chiqarish (Iyul–Dekabr)</div>
          <div style={{ display: 'flex', gap: 6 }}>
            <button className={'btn ' + (metric === 'karobka' ? 'btn--primary' : 'btn--ghost')} onClick={() => setMetric('karobka')} style={{ padding: '5px 12px', fontSize: 12 }}>Karobka</button>
            <button className={'btn ' + (metric === 'summa' ? 'btn--primary' : 'btn--ghost')} onClick={() => setMetric('summa')} style={{ padding: '5px 12px', fontSize: 12 }}>Summa</button>
          </div>
        </div>
        <FcMonthBars rows={rows} metric={metric} />
      </div>
    </div>
  );
}

window.FactoryView = FactoryView;
