/* demand-panel.jsx — 수요·재고 연동 전략 패널 (PRD: AI Demand-Driven Persona Matrix)
 *  Step 3(다이내믹 전략) + 3.2(데이터 진단)을 인터랙티브로 구동.
 *  Step 1 수요예측 모델 · 3.1 MMM 은 휴면 배너 + 데이터 요청 양식으로 정직하게 노출.
 */
(function () {
  var useState = React.useState;
  var E = window.DemandEngine;

  function Badge({ tone, children }) {
    var c = { amber: ['#3a2a12', '#f0b46a'], cyan: ['#11303a', '#5fc7e0'], plant: ['#13301f', '#5fcf94'],
              mute: ['#23262d', '#9aa0aa'], red: ['#3a1b1b', '#e08a8a'], rule: ['#2a233a', '#b79ae0'] }[tone || 'mute'];
    return <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, padding: '2px 8px', borderRadius: 4,
      fontSize: 10.5, fontFamily: 'var(--font-mono)', fontWeight: 600, background: c[0], color: c[1], whiteSpace: 'nowrap' }}>{children}</span>;
  }
  function Card({ children, style }) {
    return <div style={Object.assign({ background: 'var(--surface)', border: '1px solid var(--border)', borderRadius: 9, padding: '15px 17px' }, style)}>{children}</div>;
  }
  var H4 = function ({ children }) {
    return <h4 style={{ margin: '0 0 10px', fontSize: 11.5, letterSpacing: '0.05em', color: 'var(--ink-400)', textTransform: 'uppercase', fontFamily: 'var(--font-mono)' }}>{children}</h4>;
  };

  function DemandMatrixPanel() {
    if (!E) return <div style={{ padding: 24, color: 'var(--ink-400)' }}>DemandEngine 미로드.</div>;
    var inds = E.industries();
    var s0 = E.scenarios[0];
    var [industry, setIndustry] = useState(s0.industry);
    var [demand, setDemand] = useState(s0.demandIndex);
    var [daysLeft, setDaysLeft] = useState(s0.inventory.daysLeft);
    var [depletion, setDepletion] = useState(s0.inventory.depletion);
    // 데이터 진단 입력
    var [months, setMonths] = useState(6);
    var [stockoutFreq, setStockoutFreq] = useState(0.3);
    var [shockFreq, setShockFreq] = useState(0.2);
    var [missing, setMissing] = useState(0.15);

    function applyScenario(sc) {
      setIndustry(sc.industry); setDemand(sc.demandIndex);
      setDaysLeft(sc.inventory.daysLeft); setDepletion(sc.inventory.depletion);
    }
    var strat = E.strategy({ industry: industry, demandIndex: demand, inventory: { daysLeft: daysLeft, depletion: depletion } });
    var diag = E.diagnoseData({ months: months, stockoutFreq: stockoutFreq, shockFreq: shockFreq, missing: missing });
    var ind = E.INDUSTRY[industry];
    var gradeTone = { A: 'plant', B: 'cyan', C: 'amber', D: 'red' }[diag.grade];

    var Slider = function ({ label, value, min, max, step, on, fmt }) {
      return <label style={{ display: 'block', marginBottom: 12 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, marginBottom: 4 }}>
          <span style={{ color: 'var(--ink-300)' }}>{label}</span>
          <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--ink-100)' }}>{fmt ? fmt(value) : value}</span>
        </div>
        <input type="range" min={min} max={max} step={step || 1} value={value}
          onChange={function (e) { on(+e.target.value); }} style={{ width: '100%', accentColor: '#b79ae0' }} />
      </label>;
    };

    return (
      <div style={{ padding: '18px 20px', maxWidth: 1120, margin: '0 auto' }}>
        {/* Header */}
        <Card style={{ marginBottom: 14 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
            <strong style={{ fontFamily: 'var(--font-display)', fontSize: 16 }}>수요·재고 연동 전략 · Demand-Driven Matrix</strong>
            <Badge tone="rule">규칙 엔진</Badge>
            <Badge tone="mute">Step 3 + 3.2 활성</Badge>
            <Badge tone="amber">Step 1 모델 · MMM 휴면</Badge>
          </div>
          <p style={{ margin: '8px 0 0', fontSize: 12, lineHeight: 1.55, color: 'var(--ink-300)' }}>
            수요 예측·재고 상태를 SA·DA 광고 의사결정(타겟·입찰·소재·예산)으로 변환합니다.
            아래 수요지수·재고는 <b>시나리오 입력값</b>(향후 수요예측 모델 출력)이며, 엔진은 이를 전략으로 매핑합니다.
          </p>
        </Card>

        {/* Scenario presets */}
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 14 }}>
          {E.scenarios.map(function (sc) {
            return <button key={sc.key} onClick={function () { applyScenario(sc); }}
              style={{ padding: '7px 12px', borderRadius: 6, border: '1px solid var(--border)', cursor: 'pointer',
                background: 'var(--surface)', color: 'var(--ink-200)', fontSize: 12 }}>{sc.label}</button>;
          })}
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'minmax(280px,1fr) minmax(320px,1.4fr)', gap: 14, alignItems: 'start' }}>
          {/* LEFT — inputs */}
          <Card>
            <H4>업종 모듈</H4>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6, marginBottom: 14 }}>
              {inds.map(function (it) {
                var on = it.key === industry;
                return <button key={it.key} onClick={function () { setIndustry(it.key); }}
                  style={{ padding: '8px 10px', borderRadius: 6, cursor: 'pointer', textAlign: 'left',
                    border: '1px solid ' + (on ? '#b79ae0' : 'var(--border)'),
                    background: on ? 'rgba(183,154,224,0.12)' : 'var(--bg)', color: 'var(--ink-200)', fontSize: 12 }}>
                  <span style={{ fontSize: 14, marginRight: 5 }}>{it.icon}</span>{it.label}
                </button>;
              })}
            </div>
            <p style={{ margin: '0 0 8px', fontSize: 11, lineHeight: 1.5, color: 'var(--ink-400)' }}>{ind.note}</p>
            <div style={{ display: 'flex', gap: 5, flexWrap: 'wrap', marginBottom: 16 }}>
              {ind.drivers.map(function (d) { return <Badge key={d} tone="mute">{d}</Badge>; })}
            </div>

            <H4>시나리오 입력 (모델 출력 대체)</H4>
            <Slider label="다음 기간 수요지수" value={demand} min={60} max={160} on={setDemand} fmt={function (v) { return v + ' (평년100)'; }} />
            <Slider label="재고 소진일수" value={daysLeft} min={1} max={90} on={setDaysLeft} fmt={function (v) { return v + '일'; }} />
            <Slider label="소진 속도" value={depletion} min={0} max={1} step={0.05} on={setDepletion} fmt={function (v) { return Math.round(v * 100) + '%'; }} />
          </Card>

          {/* RIGHT — strategy output */}
          <Card style={{ borderColor: { amber: '#5a4420', cyan: '#1d4a58', plant: '#1f5536', mute: 'var(--border)' }[strat.tone] }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
              <Badge tone={strat.tone}>{strat.state}</Badge>
              <Badge tone="rule">tier · rule</Badge>
            </div>
            <strong style={{ fontFamily: 'var(--font-display)', fontSize: 17, display: 'block', margin: '6px 0 12px' }}>{strat.headline}</strong>

            <div style={{ display: 'grid', gap: 10 }}>
              <Row label="셀 활성화" items={strat.cells.activate} tone="plant" />
              {strat.cells.pause.length > 0 && <Row label="셀 일시중지" items={strat.cells.pause} tone="red" />}
              <KV k="입찰 전략" v={strat.bid} />
              <KV k="소재 방향" v={strat.creative} />
              <KV k="예산 배분" v={strat.budget} />
            </div>
            <p style={{ margin: '12px 0 0', fontSize: 10.5, lineHeight: 1.5, color: 'var(--ink-400)', borderTop: '1px solid var(--border)', paddingTop: 9 }}>
              ⚠️ {strat.caveat}
            </p>
          </Card>
        </div>

        {/* Data Diagnosis (3.2) */}
        <Card style={{ marginTop: 14 }}>
          <H4>데이터 진단 (3.2) — 현재 가능한 예측 베이스라인</H4>
          <div style={{ display: 'grid', gridTemplateColumns: 'minmax(260px,1fr) minmax(260px,1fr)', gap: 18 }}>
            <div>
              <Slider label="데이터 기간" value={months} min={1} max={36} on={setMonths} fmt={function (v) { return v + '개월'; }} />
              <Slider label="품절 빈도" value={stockoutFreq} min={0} max={1} step={0.05} on={setStockoutFreq} fmt={function (v) { return Math.round(v * 100) + '%'; }} />
              <Slider label="돌발 이벤트 빈도" value={shockFreq} min={0} max={1} step={0.05} on={setShockFreq} fmt={function (v) { return Math.round(v * 100) + '%'; }} />
              <Slider label="결측 비율" value={missing} min={0} max={1} step={0.05} on={setMissing} fmt={function (v) { return Math.round(v * 100) + '%'; }} />
            </div>
            <div>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginBottom: 8 }}>
                <span style={{ fontFamily: 'var(--font-display)', fontSize: 38, fontWeight: 700, lineHeight: 1 }}>{diag.score}</span>
                <Badge tone={gradeTone}>등급 {diag.grade}</Badge>
              </div>
              <p style={{ margin: '0 0 10px', fontSize: 12.5, color: 'var(--ink-200)', lineHeight: 1.5 }}><b>가능 수준:</b> {diag.horizon}</p>
              {diag.warnings.length > 0 ? diag.warnings.map(function (w, i) {
                return <p key={i} style={{ margin: '0 0 5px', fontSize: 11, color: '#e0a86a', lineHeight: 1.45 }}>⚠ {w}</p>;
              }) : <p style={{ fontSize: 11, color: 'var(--ink-400)' }}>주요 경고 없음.</p>}
              <p style={{ margin: '8px 0 0', fontSize: 10.5, color: 'var(--ink-400)' }}>정확도(%)에 집착하지 않고 "왜 맞고 왜 틀리는지" 메타를 함께 봅니다(PRD §4).</p>
            </div>
          </div>
        </Card>

        {/* Dormant modules */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(300px,1fr))', gap: 14, marginTop: 14 }}>
          {[E.dormant.forecast, E.dormant.mmm].map(function (m) {
            return <div key={m.name} style={{ background: 'var(--surface)', border: '1px dashed var(--border)', borderRadius: 9, padding: '15px 17px' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
                <Badge tone="cyan">휴면</Badge>
                <strong style={{ fontSize: 13 }}>{m.name}</strong>
              </div>
              <p style={{ margin: '0 0 10px', fontSize: 11.5, lineHeight: 1.55, color: 'var(--ink-300)' }}>{m.note}</p>
              <div style={{ fontSize: 11, color: 'var(--ink-400)' }}>
                <div style={{ marginBottom: 4, fontFamily: 'var(--font-mono)' }}>필요 데이터:</div>
                <ul style={{ margin: 0, paddingLeft: 16, lineHeight: 1.6 }}>
                  {m.needs.map(function (n) { return <li key={n}>{n}</li>; })}
                </ul>
              </div>
            </div>;
          })}
        </div>
        <p style={{ margin: '12px 2px 0', fontSize: 11, color: 'var(--ink-400)', lineHeight: 1.5 }}>
          위 휴면 모듈은 실측 RAW 데이터를 받으면 활성화됩니다. 데이터 요청 양식은 <code style={{ fontFamily: 'var(--font-mono)' }}>docs/DATA_REQUESTS.md</code> 참고.
        </p>
      </div>
    );
  }

  function Row({ label, items, tone }) {
    return <div>
      <div style={{ fontSize: 11, color: 'var(--ink-400)', fontFamily: 'var(--font-mono)', marginBottom: 4 }}>{label}</div>
      <div style={{ display: 'flex', gap: 5, flexWrap: 'wrap' }}>
        {items.length ? items.map(function (it) { return <Badge key={it} tone={tone}>{it}</Badge>; }) : <span style={{ fontSize: 12, color: 'var(--ink-400)' }}>—</span>}
      </div>
    </div>;
  }
  function KV({ k, v }) {
    return <div>
      <div style={{ fontSize: 11, color: 'var(--ink-400)', fontFamily: 'var(--font-mono)', marginBottom: 3 }}>{k}</div>
      <div style={{ fontSize: 12.5, color: 'var(--ink-100)', lineHeight: 1.5 }}>{v}</div>
    </div>;
  }

  Object.assign(window, { DemandMatrixPanel: DemandMatrixPanel });
})();
