// screen-settings-score.jsx — Deal Score Engine editor + live preview
// Edits brand weights, discount tiers, price-VND tiers, multipliers & bonuses.
// Right pane recomputes top products in real time so admin can see impact
// before saving. Save is local-only in this prototype (toast confirm).
const { useState: useStateScore, useMemo: useMemoScore } = React;

/* Initial brand weights pulled from BRANDS[].weight */
function initBrandWeights() {
  const w = {};
  BRANDS.forEach(b => { w[b.key] = b.weight || 5; });
  return w;
}

/* Pure scorer used by the preview pane.
 * Mirrors data.jsx::calcScore but accepts a brand-weights override map. */
function runScoreLocal(p, cfg, weights) {
  const b = brandOf(p.brand);
  const bw = weights[p.brand] !== undefined ? weights[p.brand] : (b.weight || 5);
  const br = {};
  br.brand = bw * (cfg.brandWeightFactor || 0);
  const tier = cfg.discountTiers.find(t => p.disc >= t.min);
  br.discount = tier ? tier.score : 0;
  br.discountLabel = tier ? tier.label : '';
  br.coupon = Math.round((p.couponPercent || 0) * (cfg.couponMultiplier || 0));
  const finalVnd = p.priceVnd || p.vnd || 0;
  const vTier = cfg.priceVndTiers.find(t => finalVnd <= t.max);
  br.priceFriendly = vTier ? vTier.score : 0;
  br.priceFriendlyLabel = vTier ? vTier.label : '';
  br.watchlist = p.watchlistMatch ? (cfg.watchlistBonus || 0) : 0;
  const sRatio = p.sizeTotal > 0 ? (p.sizeAvail || 0) / p.sizeTotal : 0;
  if (sRatio >= 0.8) br.size = cfg.sizeAvailFullBonus || 0;
  else if (sRatio >= 0.5) br.size = cfg.sizeAvailHalfBonus || 0;
  else br.size = 0;
  br.confidence = (cfg.confidenceBonus || {})[p.confidence || 'medium'] || 0;
  br.total = Math.min(100, Math.round(
    br.brand + br.discount + br.coupon + br.priceFriendly +
    br.watchlist + br.size + br.confidence
  ));
  return br;
}

/* Deep clone helper for cfg reset */
function cloneCfg(c) {
  return {
    ...c,
    discountTiers: c.discountTiers.map(t => ({ ...t })),
    priceVndTiers: c.priceVndTiers.map(t => ({ ...t })),
    confidenceBonus: { ...c.confidenceBonus },
  };
}

/* ========================= MAIN ========================= */
function SettingsScoreScreen() {
  const app = useApp();
  const [cfg, setCfg] = useStateScore(cloneCfg(SCORING_CONFIG));
  const [weights, setWeights] = useStateScore(initBrandWeights());
  const [dirty, setDirty] = useStateScore(false);

  function update(patch) { setCfg(c => ({ ...c, ...patch })); setDirty(true); }
  function updateTier(key, idx, patch) {
    setCfg(c => ({ ...c, [key]: c[key].map((t, i) => i === idx ? { ...t, ...patch } : t) }));
    setDirty(true);
  }
  function updateWeight(brandKey, val) {
    setWeights(w => ({ ...w, [brandKey]: Math.max(0, Math.min(10, val)) }));
    setDirty(true);
  }
  function reset() {
    setCfg(cloneCfg(SCORING_CONFIG));
    setWeights(initBrandWeights());
    setDirty(false);
    app.toast && app.toast('Đã khôi phục cấu hình mặc định', 'rotate');
  }
  function save() {
    setDirty(false);
    app.toast && app.toast('Đã lưu cấu hình Deal Score (demo: local session)', 'check');
  }

  /* Recompute everything when cfg/weights change */
  const rows = useMemoScore(() => {
    return PRODUCTS.map(p => {
      const next = runScoreLocal(p, cfg, weights);
      const orig = p.scoreBreakdown || p.score || 0;
      const origTotal = orig.total !== undefined ? orig.total : (p.score || 0);
      return { p, next, origTotal, diff: next.total - origTotal };
    }).sort((a, b) => b.next.total - a.next.total);
  }, [cfg, weights]);

  const topN = rows.slice(0, 10);
  const stats = useMemoScore(() => {
    const autoCount = rows.filter(r => r.next.total >= cfg.autoRouteThreshold).length;
    const postableCount = rows.filter(r => r.next.total >= cfg.minPostableScore).length;
    const avg = Math.round(rows.reduce((s, r) => s + r.next.total, 0) / rows.length);
    return { autoCount, postableCount, avg };
  }, [rows, cfg.autoRouteThreshold, cfg.minPostableScore]);

  return (
    <div className="page-pad wide" style={{ paddingTop: 14 }}>
      {/* Toolbar */}
      <div className="row gap-sm" style={{ marginBottom: 14, flexWrap: 'wrap' }}>
        <div style={{ flex: 1, minWidth: 220 }}>
          <div className="t-h1">Deal Score Engine</div>
          <div className="t-sm dim" style={{ marginTop: 2 }}>
            Quy tắc xếp hạng sản phẩm. Điều chỉnh trọng số bên trái, xem ngay top 10 cập nhật bên phải.
          </div>
        </div>
        <Button variant="ghost" size="sm" icon="rotate" onClick={reset}>Khôi phục mặc định</Button>
        <Button variant="primary" size="sm" icon="save" onClick={save} disabled={!dirty}>
          {dirty ? 'Lưu thay đổi' : 'Đã lưu'}
        </Button>
      </div>

      {/* Header stats */}
      <div className="stat-grid" style={{ marginBottom: 16 }}>
        <StatTile label="Điểm TB toàn pool" value={stats.avg} suffix="/100" tone={stats.avg >= 60 ? 'green' : stats.avg >= 40 ? 'yellow' : 'red'} />
        <StatTile label={`Auto-route (≥ ${cfg.autoRouteThreshold})`} value={stats.autoCount} suffix={` / ${rows.length}`} tone="accent" />
        <StatTile label={`Đủ ngưỡng đăng (≥ ${cfg.minPostableScore})`} value={stats.postableCount} suffix={` / ${rows.length}`} tone="blue" />
        <StatTile label="Brand được nâng" value={Object.keys(weights).filter(k => weights[k] !== brandOf(k).weight).length} suffix=" brand" tone="dim" />
      </div>

      <div className="score-grid">
        {/* ==================== LEFT: EDITOR ==================== */}
        <div>
          {/* Multipliers */}
          <Section title="Trọng số & multiplier" desc="Yếu tố nhân điểm áp dụng cho mọi sản phẩm">
            <div className="grid-2" style={{ gap: 14 }}>
              <Field label="Brand weight × hệ số" hint="Điểm brand = weight × hệ số">
                <NumInput value={cfg.brandWeightFactor} onChange={v => update({ brandWeightFactor: v })} min={0} max={10} step={0.5} />
              </Field>
              <Field label="Coupon multiplier" hint="Điểm coupon = % coupon × hệ số">
                <NumInput value={cfg.couponMultiplier} onChange={v => update({ couponMultiplier: v })} min={0} max={2} step={0.1} />
              </Field>
              <Field label="Watchlist bonus" hint="Cộng khi khớp watchlist active">
                <NumInput value={cfg.watchlistBonus} onChange={v => update({ watchlistBonus: v })} min={0} max={40} />
              </Field>
              <Field label="Size đủ size (≥ 80%)" hint="Bonus khi còn nhiều size">
                <NumInput value={cfg.sizeAvailFullBonus} onChange={v => update({ sizeAvailFullBonus: v })} min={0} max={20} />
              </Field>
              <Field label="Size còn 1 nửa (≥ 50%)" hint="Bonus khi size còn vừa phải">
                <NumInput value={cfg.sizeAvailHalfBonus} onChange={v => update({ sizeAvailHalfBonus: v })} min={0} max={20} />
              </Field>
              <Field label="Auto-route threshold" hint="Score ≥ giá trị này → tạo content nháp">
                <NumInput value={cfg.autoRouteThreshold} onChange={v => update({ autoRouteThreshold: v })} min={0} max={100} />
              </Field>
              <Field label="Min postable" hint="Dưới ngưỡng không cho đăng">
                <NumInput value={cfg.minPostableScore} onChange={v => update({ minPostableScore: v })} min={0} max={100} />
              </Field>
            </div>
            <div className="divider"></div>
            <div className="t-2xs strong dimmer" style={{ marginBottom: 8 }}>BONUS THEO ĐỘ TIN CẬY DỮ LIỆU</div>
            <div className="grid-3" style={{ gap: 14 }}>
              {['high', 'medium', 'low'].map(k => (
                <Field key={k} label={'Confidence ' + k}>
                  <NumInput value={cfg.confidenceBonus[k]} onChange={v => update({ confidenceBonus: { ...cfg.confidenceBonus, [k]: v } })} min={0} max={20} />
                </Field>
              ))}
            </div>
          </Section>

          {/* Brand weights */}
          <Section title="Brand weight" desc={`Trọng số chất lượng 1-10 cho ${BRANDS.length} brand. Brand mạnh = điểm khởi đầu cao.`}>
            <div className="brand-weight-grid">
              {BRANDS.map(b => (
                <div key={b.key} className="brand-weight-row">
                  <div className="row gap-sm" style={{ flex: 1, minWidth: 0 }}>
                    <BrandLogo brand={b} size={22} />
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div className="t-sm strong clip-1">{b.name}</div>
                      <div className="t-2xs dimmer clip-1">{b.kind}{b.isFallback ? ' · fallback' : ''}{b.disabledReason ? ' · disabled' : ''}</div>
                    </div>
                  </div>
                  <input type="range" min="0" max="10" value={weights[b.key]}
                    onChange={e => updateWeight(b.key, +e.target.value)}
                    style={{ width: 110, accentColor: 'var(--accent)' }} />
                  <input type="number" className="input sm" min="0" max="10"
                    value={weights[b.key]} onChange={e => updateWeight(b.key, +e.target.value)}
                    style={{ width: 56, textAlign: 'right' }} />
                </div>
              ))}
            </div>
          </Section>

          {/* Discount tiers */}
          <Section title="Bậc giảm giá" desc="Tier theo % giảm. Cao nhất khớp trước.">
            <table className="tbl">
              <thead>
                <tr>
                  <th style={{ width: 90 }}>Từ %</th>
                  <th style={{ width: 90 }}>Điểm</th>
                  <th>Nhãn hiển thị</th>
                </tr>
              </thead>
              <tbody>
                {cfg.discountTiers.map((t, i) => (
                  <tr key={i} style={{ cursor: 'default' }}>
                    <td><NumInput value={t.min} onChange={v => updateTier('discountTiers', i, { min: v })} min={0} max={100} small /></td>
                    <td><NumInput value={t.score} onChange={v => updateTier('discountTiers', i, { score: v })} min={0} max={100} small /></td>
                    <td><input className="input sm" value={t.label} onChange={e => updateTier('discountTiers', i, { label: e.target.value })} /></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </Section>

          {/* Price VND tiers */}
          <Section title="Bậc giá VND" desc="Tier theo giá VND đã cộng ship + margin. Thấp nhất khớp trước.">
            <table className="tbl">
              <thead>
                <tr>
                  <th style={{ width: 140 }}>Đến VND</th>
                  <th style={{ width: 90 }}>Điểm</th>
                  <th>Nhãn hiển thị</th>
                </tr>
              </thead>
              <tbody>
                {cfg.priceVndTiers.map((t, i) => (
                  <tr key={i} style={{ cursor: 'default' }}>
                    <td>
                      {t.max === Infinity
                        ? <span className="t-sm dimmer mono">∞ (luxury)</span>
                        : <NumInput value={t.max} onChange={v => updateTier('priceVndTiers', i, { max: v })} min={0} max={20000000} step={50000} small />
                      }
                    </td>
                    <td><NumInput value={t.score} onChange={v => updateTier('priceVndTiers', i, { score: v })} min={0} max={100} small /></td>
                    <td><input className="input sm" value={t.label} onChange={e => updateTier('priceVndTiers', i, { label: e.target.value })} /></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </Section>
        </div>

        {/* ==================== RIGHT: PREVIEW ==================== */}
        <div>
          <div className="card card-pad preview-card">
            <div className="row gap-sm" style={{ marginBottom: 12 }}>
              <Icon name="trending" size={16} style={{ color: 'var(--accent)' }} />
              <div style={{ flex: 1 }}>
                <div className="t-h2">Top 10 sau khi áp dụng</div>
                <div className="t-2xs dimmer">Bảng breakdown chi tiết — cập nhật real-time khi đổi config bên trái.</div>
              </div>
            </div>

            <table className="tbl breakdown-tbl">
              <thead>
                <tr>
                  <th style={{ width: 24 }}>#</th>
                  <th>Sản phẩm</th>
                  <th style={{ width: 56, textAlign: 'right' }}>Điểm</th>
                  <th style={{ width: 50, textAlign: 'right' }}>Δ</th>
                  <th style={{ width: 30, textAlign: 'right' }} title="Brand">B</th>
                  <th style={{ width: 30, textAlign: 'right' }} title="Discount">D</th>
                  <th style={{ width: 30, textAlign: 'right' }} title="Coupon">C</th>
                  <th style={{ width: 30, textAlign: 'right' }} title="Price VND friendly">V</th>
                  <th style={{ width: 30, textAlign: 'right' }} title="Watchlist">W</th>
                  <th style={{ width: 30, textAlign: 'right' }} title="Size">S</th>
                  <th style={{ width: 30, textAlign: 'right' }} title="Confidence">I</th>
                </tr>
              </thead>
              <tbody>
                {topN.map((r, i) => {
                  const b = brandOf(r.p.brand);
                  const diffCls = r.diff > 0 ? 'diff-up' : r.diff < 0 ? 'diff-down' : 'diff-neu';
                  return (
                    <tr key={r.p.id} style={{ cursor: 'default' }}>
                      <td className="t-2xs dimmer mono">{i + 1}</td>
                      <td>
                        <div className="row gap-sm" style={{ gap: 6 }}>
                          <BrandLogo brand={b} size={18} />
                          <div style={{ minWidth: 0, flex: 1 }}>
                            <div className="t-xs strong clip-1">{r.p.titleVn}</div>
                            <div className="t-2xs dimmer clip-1 mono">{r.p.sku} · {fmtJPY(r.p.jpy)}{r.p.couponPercent ? ' · coupon ' + r.p.couponPercent + '%' : ''}</div>
                          </div>
                          {r.p.watchlistMatch && <Icon name="star" size={12} style={{ color: 'var(--yellow)' }} title={'Watchlist · ' + r.p.watchlistMatch.keyword} />}
                        </div>
                      </td>
                      <td style={{ textAlign: 'right' }}><Score value={r.next.total} /></td>
                      <td className={'t-2xs strong mono ' + diffCls} style={{ textAlign: 'right' }}>
                        {r.diff > 0 ? '+' + r.diff : r.diff}
                      </td>
                      <td className="t-2xs mono dim" style={{ textAlign: 'right' }}>{r.next.brand}</td>
                      <td className="t-2xs mono dim" style={{ textAlign: 'right' }}>{r.next.discount}</td>
                      <td className="t-2xs mono dim" style={{ textAlign: 'right' }}>{r.next.coupon || '–'}</td>
                      <td className="t-2xs mono dim" style={{ textAlign: 'right' }}>{r.next.priceFriendly}</td>
                      <td className="t-2xs mono dim" style={{ textAlign: 'right' }}>{r.next.watchlist || '–'}</td>
                      <td className="t-2xs mono dim" style={{ textAlign: 'right' }}>{r.next.size || '–'}</td>
                      <td className="t-2xs mono dim" style={{ textAlign: 'right' }}>{r.next.confidence}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>

            <div className="divider"></div>
            <div className="t-2xs dimmer" style={{ lineHeight: 1.7 }}>
              <span className="strong">Legend:</span> B brand · D discount tier · C coupon · V price-VND friendliness · W watchlist · S size availability · I info confidence. Tổng cap 100.
            </div>
          </div>

          {/* Formula explainer */}
          <div className="card card-pad" style={{ marginTop: 14 }}>
            <div className="t-h2" style={{ marginBottom: 8 }}>Công thức</div>
            <pre className="mono t-2xs" style={{
              background: 'var(--bg-2)', padding: 12, borderRadius: 'var(--r-md)',
              border: '1px solid var(--border)', overflow: 'auto', lineHeight: 1.6, margin: 0
            }}>
{`score = brand_weight × ${cfg.brandWeightFactor}        // chất lượng nguồn
      + discount_tier_score             // bậc % giảm
      + coupon_% × ${cfg.couponMultiplier}             // coupon Rakuten/Amazon
      + vnd_friendliness_tier_score     // giá VN-friendly
      + (watchlist ? ${cfg.watchlistBonus} : 0)         // khớp keyword theo dõi
      + size_availability_bonus         // tỉ lệ size còn hàng
      + confidence_bonus                // dữ liệu sạch hay nhiễu
score = min(100, round(score))`}
            </pre>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ========================= Sub primitives ========================= */
function NumInput({ value, onChange, min = 0, max = 999999, step = 1, small }) {
  return (
    <input type="number"
      className={'input ' + (small ? 'sm' : '')}
      value={value} min={min} max={max} step={step}
      onChange={e => {
        const v = e.target.value === '' ? 0 : Number(e.target.value);
        if (!Number.isNaN(v)) onChange(v);
      }}
      style={small ? { width: '100%' } : {}} />
  );
}

function StatTile({ label, value, suffix, tone }) {
  const toneClr = {
    green: 'var(--green)', yellow: 'var(--yellow)', red: 'var(--red)',
    accent: 'var(--accent)', blue: 'var(--blue)', dim: 'var(--text-3)'
  }[tone] || 'var(--text)';
  return (
    <div className="stat">
      <div className="t-2xs strong dimmer" style={{ marginBottom: 6, letterSpacing: '.06em' }}>{label.toUpperCase()}</div>
      <div className="mono" style={{ fontSize: 22, fontWeight: 700, color: toneClr }}>
        {value}<span className="t-sm dimmer" style={{ fontWeight: 500, marginLeft: 2 }}>{suffix}</span>
      </div>
    </div>
  );
}

Object.assign(window, { SettingsScoreScreen });
