// ────────────────────────────────────────────────────────────────────
// AW-008 · Partner Feature Settings Modal — 640px
// ────────────────────────────────────────────────────────────────────

// Local toggle with caption slot
const BigToggle = ({ on, disabled }) => (
  <div style={{
    width: 44, height: 24, borderRadius: 12,
    background: disabled ? 'var(--n-200)' : (on ? 'var(--primary)' : 'var(--n-300)'),
    position: 'relative', flexShrink: 0,
    transition: 'background 120ms',
    opacity: disabled ? 0.7 : 1,
  }}>
    <div style={{
      position: 'absolute', top: 2, left: on ? 22 : 2,
      width: 20, height: 20, borderRadius: '50%',
      background: '#fff',
      boxShadow: '0 1px 3px rgba(0,0,0,0.25)',
      transition: 'left 120ms',
    }}/>
  </div>
);

// Gradient slider: neutral → warning → error with thumb
const RangeBar = ({ value, disabled, max = 50 }) => {
  const pct = Math.min(100, (value / max) * 100);
  const clampedValue = Math.max(0, Math.min(max, value));
  const valueColor = value > max ? 'var(--error)' : (value >= 25 ? 'var(--warning)' : (value > 0 ? 'var(--n-700)' : 'var(--n-500)'));

  return (
    <div style={{ marginTop: 8, opacity: disabled ? 0.5 : 1 }}>
      <div style={{
        position: 'relative',
        height: 8, borderRadius: 4,
        background: 'linear-gradient(90deg, #E5E7EB 0%, #FDE68A 50%, #FECACA 100%)',
        marginTop: 6,
      }}>
        {/* Tick marks */}
        {[0, 25, 50].map(t => (
          <div key={t} style={{
            position: 'absolute', top: -3, bottom: -3,
            left: `${(t / max) * 100}%`,
            width: 1, background: 'var(--n-300)',
            transform: 'translateX(-0.5px)',
          }}/>
        ))}
        {/* Thumb */}
        <div style={{
          position: 'absolute', top: -5, left: `${pct}%`,
          transform: 'translateX(-50%)',
          width: 18, height: 18, borderRadius: '50%',
          background: '#fff',
          border: `2px solid ${valueColor}`,
          boxShadow: '0 1px 4px rgba(0,0,0,0.2)',
        }}/>
      </div>
      <div style={{
        display: 'flex', marginTop: 6,
        fontFamily: 'JetBrains Mono, monospace', fontSize: 10, color: 'var(--n-500)',
      }}>
        <span>0%</span>
        <span style={{ margin: '0 auto' }}>25%</span>
        <span style={{ marginLeft: 'auto' }}>50%</span>
      </div>
    </div>
  );
};

// Small caption inline error
const InlineError = ({ children, code }) => (
  <div style={{
    display: 'inline-flex', alignItems: 'center', gap: 5,
    marginTop: 6,
    fontSize: 12, color: 'var(--error)',
  }}>
    <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12" y2="16.01"/>
    </svg>
    <span>{children}</span>
    {code && <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 11, color: '#991B1B' }}>({code})</span>}
  </div>
);

// Field row wrapper
const FeatField = ({ title, children, caption }) => (
  <div style={{
    padding: '18px 20px',
    background: '#fff',
    border: '1px solid var(--n-200)',
    borderRadius: 8,
    marginBottom: 12,
  }}>
    {title && (
      <div style={{
        fontFamily: 'Inter', fontSize: 11, fontWeight: 700, letterSpacing: '0.06em',
        color: 'var(--n-500)', textTransform: 'uppercase', marginBottom: 10,
      }}>{title}</div>
    )}
    {children}
    {caption && (
      <div style={{
        marginTop: 10, paddingTop: 10,
        borderTop: '1px dashed var(--n-200)',
        fontSize: 12, color: 'var(--n-500)', lineHeight: 1.5,
      }}>{caption}</div>
    )}
  </div>
);

// History row
const HistoryRow = ({ when, who, change, memo }) => (
  <div style={{
    display: 'grid',
    gridTemplateColumns: '160px 1fr',
    gap: 12,
    padding: '10px 0',
    borderBottom: '1px dashed var(--n-200)',
    fontSize: 12,
  }}>
    <div>
      <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 11, color: 'var(--n-900)' }}>{when}</div>
      <div style={{ fontFamily: 'Inter', fontSize: 11, color: 'var(--n-500)', marginTop: 2 }}>{who}</div>
    </div>
    <div>
      <div style={{ color: 'var(--n-900)', fontFamily: 'Inter', fontSize: 12, display: 'flex', flexWrap: 'wrap', gap: 6 }}>
        {change.map((c, i) => (
          <span key={i} style={{
            fontFamily: 'JetBrains Mono, monospace', fontSize: 11,
            padding: '1px 6px', borderRadius: 3,
            background: 'var(--n-100)', color: 'var(--n-700)',
          }}>{c}</span>
        ))}
      </div>
      {memo && <div style={{ marginTop: 4, color: 'var(--n-500)', fontSize: 11 }}>{memo}</div>}
    </div>
  </div>
);

// Warning banner (SUSPENDED / batch conflict)
const FeatBanner = ({ kind, children, code }) => {
  const style = kind === 'batch' ? {
    bg: 'var(--error-bg)', border: '#FECACA', icon: 'var(--error)', text: '#991B1B',
  } : {
    bg: 'var(--warning-bg)', border: '#FDE68A', icon: 'var(--warning)', text: '#78350F',
  };
  return (
    <div style={{
      display: 'flex', alignItems: 'flex-start', gap: 10,
      padding: '12px 14px',
      background: style.bg, border: `1px solid ${style.border}`,
      borderRadius: 6, marginBottom: 12,
    }}>
      <div style={{ color: style.icon, marginTop: 1, flexShrink: 0 }}>
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
          <path d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/>
          <line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12" y2="17.01"/>
        </svg>
      </div>
      <div style={{ flex: 1, fontSize: 12.5, color: style.text, lineHeight: 1.5 }}>
        {children}
        {code && <span style={{ marginLeft: 6, fontFamily: 'JetBrains Mono, monospace', fontSize: 11, opacity: 0.9 }}>({code})</span>}
      </div>
    </div>
  );
};

// Diff confirm dialog
const FeatConfirmDialog = () => (
  <div style={{
    position: 'absolute', inset: 0,
    background: 'rgba(17,24,39,0.65)',
    display: 'grid', placeItems: 'center',
    zIndex: 10,
  }}>
    <div style={{
      width: 440, background: '#fff',
      borderRadius: 12, boxShadow: '0 8px 24px rgba(0,0,0,0.25)',
      padding: 24,
    }}>
      <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--n-900)', marginBottom: 4 }}>설정 변경 확인</div>
      <div style={{ fontSize: 12, color: 'var(--n-500)', marginBottom: 14 }}>{PARTNER_DETAIL.name} · <span style={{ fontFamily: 'JetBrains Mono, monospace' }}>{PARTNER_DETAIL.id}</span></div>

      <div style={{
        background: 'var(--n-050)',
        border: '1px solid var(--n-200)',
        borderRadius: 6, padding: '12px 14px',
        marginBottom: 14,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '4px 0' }}>
          <div style={{ width: 130, fontSize: 12, color: 'var(--n-500)' }}>수동 사용처리</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontFamily: 'JetBrains Mono, monospace', fontSize: 12 }}>
            <span style={{ color: 'var(--n-500)', padding: '1px 6px', background: '#fff', border: '1px solid var(--n-200)', borderRadius: 3 }}>OFF</span>
            <span style={{ color: 'var(--n-500)' }}>→</span>
            <span style={{ color: 'var(--primary-pressed)', padding: '1px 6px', background: 'var(--primary-hover-bg)', borderRadius: 3, fontWeight: 600 }}>ON</span>
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '4px 0' }}>
          <div style={{ width: 130, fontSize: 12, color: 'var(--n-500)' }}>EXPIRED 정산 비율</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontFamily: 'JetBrains Mono, monospace', fontSize: 12 }}>
            <span style={{ color: 'var(--n-500)', padding: '1px 6px', background: '#fff', border: '1px solid var(--n-200)', borderRadius: 3 }}>10.0%</span>
            <span style={{ color: 'var(--n-500)' }}>→</span>
            <span style={{ color: 'var(--warning)', padding: '1px 6px', background: 'var(--warning-bg)', borderRadius: 3, fontWeight: 600 }}>15.0%</span>
          </div>
        </div>
      </div>

      <div style={{ fontSize: 12, color: 'var(--n-700)', lineHeight: 1.5, marginBottom: 16 }}>
        변경 내역은 <strong>감사 로그</strong>에 기록되며 파트너에게 즉시 반영됩니다.
      </div>

      <div style={{ display: 'flex', gap: 8 }}>
        <button style={{
          flex: 1, height: 40,
          background: '#fff', border: '1px solid var(--n-300)',
          borderRadius: 6, cursor: 'pointer',
          fontFamily: 'Inter', fontSize: 13, fontWeight: 600, color: 'var(--n-700)',
        }}>돌아가기</button>
        <button style={{
          flex: 1, height: 40,
          background: 'var(--primary)', border: 'none', color: '#fff',
          borderRadius: 6, cursor: 'pointer',
          fontFamily: 'Inter', fontSize: 13, fontWeight: 600,
        }}>저장 확인</button>
      </div>
    </div>
  </div>
);

// Footer
const FeatFooter = ({ canSave }) => (
  <div style={{
    display: 'flex', alignItems: 'center', justifyContent: 'flex-end',
    gap: 8,
    padding: '14px 24px',
    borderTop: '1px solid var(--n-200)',
    background: '#fff',
  }}>
    <button style={{
      height: 40, padding: '0 18px',
      background: '#fff', border: '1px solid var(--n-300)',
      color: 'var(--n-700)', borderRadius: 6,
      fontFamily: 'Inter', fontSize: 13, fontWeight: 600, cursor: 'pointer',
    }}>취소</button>
    <button disabled={!canSave} style={{
      height: 40, padding: '0 22px',
      background: canSave ? 'var(--primary)' : 'var(--n-200)',
      color: canSave ? '#fff' : 'var(--n-500)',
      border: 'none', borderRadius: 6,
      fontFamily: 'Inter', fontSize: 13, fontWeight: 600,
      cursor: canSave ? 'pointer' : 'not-allowed',
    }}>저장</button>
  </div>
);

// Main modal
const FeatureSettingsModal = ({ variant = 'pristine' }) => {
  // Scenarios
  const isPristine    = variant === 'pristine';
  const isDirty       = variant === 'dirty';
  const isConfirm     = variant === 'confirm';
  const isSuspended   = variant === 'suspended';
  const isBatch       = variant === 'batch-conflict';
  const isOutOfRange  = variant === 'out-of-range';

  const disabled = isSuspended;
  const manualOn = isPristine ? true : (isDirty || isConfirm || isSuspended ? true : true);
  const rate =
    isOutOfRange ? 62.5 :
    isDirty || isConfirm || isBatch ? 15.0 :
    10.0;
  const dirty = isDirty || isBatch || isOutOfRange;
  const canSave = dirty && !isOutOfRange && !isSuspended;

  return (
    <>
      <Modal width={640}>
        <ModalHeader
          title={`기능 설정 — ${PARTNER_DETAIL.name}`}
          pill={<PrtBadge status={isSuspended ? 'SUSPENDED' : 'APPROVED'}/>}
        />
        <div style={{
          padding: '18px 24px',
          flex: 1,
          background: 'var(--n-050)',
        }}>
          {/* Banners */}
          {isSuspended && (
            <FeatBanner kind="warn" code="WARN-005">
              <strong>파트너가 SUSPENDED 상태입니다.</strong> 운영 재개 전까지 기능 설정을 변경할 수 없습니다. 파트너 운영 재개는 AW-006에서 가능합니다.
            </FeatBanner>
          )}
          {isBatch && (
            <FeatBanner kind="batch" code="HTTP-409">
              <strong>정산 배치가 진행 중입니다.</strong> 배치 완료(~18분 남음) 후 다시 시도해 주세요. 현재 변경은 저장되지 않습니다.
            </FeatBanner>
          )}

          {/* Partner summary strip */}
          <div style={{
            display: 'flex', alignItems: 'center', gap: 10,
            padding: '10px 12px', marginBottom: 14,
            background: '#fff', border: '1px solid var(--n-200)', borderRadius: 6,
          }}>
            <CatIcon kind={PARTNER_DETAIL.cat} size={32}/>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--n-900)' }}>{PARTNER_DETAIL.name}</div>
              <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 11, color: 'var(--n-500)' }}>{PARTNER_DETAIL.id} · {CAT[PARTNER_DETAIL.cat].label}</div>
            </div>
          </div>

          {/* Field 1 — Manual redeem */}
          <FeatField
            title="수동 사용처리"
            caption={<>ON 설정 시 PW-006 / PW-007 메뉴가 해당 파트너에 노출되며, QR 스캔 외 수동 승인이 가능해집니다.</>}
          >
            <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
              <BigToggle on={manualOn} disabled={disabled}/>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14, fontWeight: 600, color: disabled ? 'var(--n-500)' : 'var(--n-900)' }}>
                  수동 사용처리 활성화
                </div>
                <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 11, color: 'var(--n-500)', marginTop: 2 }}>
                  {manualOn ? 'ON' : 'OFF'}
                  {isDirty || isConfirm ? (
                    <span style={{ marginLeft: 8, color: 'var(--warning)' }}>· 변경됨 (OFF → ON)</span>
                  ) : null}
                </div>
              </div>
            </div>
          </FeatField>

          {/* Field 2 — EXPIRED settlement rate */}
          <FeatField
            title="EXPIRED 정산 비율"
            caption={<>기본 0.0% (정산 제외). <strong>계약 기반으로만 설정 가능</strong>하며, 변경 시 다음 정산 사이클부터 반영됩니다.</>}
          >
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 14 }}>
              <div style={{
                display: 'flex', alignItems: 'center',
                background: '#fff',
                border: `1px solid ${isOutOfRange ? 'var(--error)' : 'var(--n-300)'}`,
                borderRadius: 6, padding: '0 4px 0 12px',
                width: 160,
                opacity: disabled ? 0.5 : 1,
              }}>
                <span style={{
                  fontFamily: 'JetBrains Mono, monospace', fontSize: 20, fontWeight: 600,
                  color: isOutOfRange ? 'var(--error)' : 'var(--n-900)',
                  fontVariantNumeric: 'tabular-nums',
                  lineHeight: 1.6,
                }}>{rate.toFixed(1)}</span>
                <span style={{ fontSize: 13, color: 'var(--n-500)', marginLeft: 4, marginRight: 'auto' }}>%</span>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
                  <button style={numBtn}>▲</button>
                  <button style={numBtn}>▼</button>
                </div>
              </div>
              <div style={{ flex: 1 }}>
                <RangeBar value={rate > 50 ? 50 : rate} disabled={disabled}/>
              </div>
            </div>
            {isOutOfRange && <InlineError>0.0% ~ 50.0% 범위여야 합니다. 입력값: 62.5%</InlineError>}
            {(isDirty || isConfirm) && !isOutOfRange && (
              <div style={{
                display: 'inline-flex', alignItems: 'center', gap: 5,
                marginTop: 8, fontSize: 12, color: 'var(--warning)',
              }}>
                <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/>
                </svg>
                변경됨 · <span style={{ fontFamily: 'JetBrains Mono, monospace' }}>10.0% → 15.0%</span>
              </div>
            )}
          </FeatField>

          {/* Field 3 — Memo */}
          <FeatField title={<>계약 근거 메모 <span style={{ fontWeight: 500, color: 'var(--n-500)', letterSpacing: 0, textTransform: 'none' }}>· 선택</span></>}>
            <textarea
              disabled={disabled}
              placeholder="계약서 문서 번호 + 변경 사유 (예: CNT-2026-0418 · 본사 협의 결과 반영)"
              defaultValue={isDirty || isConfirm ? 'CNT-2026-0418 · 본사 협의 결과, Q2 전환기 정산 비율 조정' : ''}
              style={{
                width: '100%', minHeight: 68,
                border: '1px solid var(--n-300)', borderRadius: 6,
                padding: '10px 12px', boxSizing: 'border-box',
                fontFamily: 'Pretendard, Inter, sans-serif', fontSize: 13, color: 'var(--n-900)',
                resize: 'vertical', outline: 'none',
                background: disabled ? 'var(--n-100)' : '#fff',
              }}
            />
            <div style={{ display: 'flex', marginTop: 4 }}>
              <div style={{ marginLeft: 'auto', fontFamily: 'JetBrains Mono, monospace', fontSize: 10, color: 'var(--n-500)' }}>
                {(isDirty || isConfirm ? 42 : 0)} / 200
              </div>
            </div>
          </FeatField>

          {/* History */}
          <div style={{
            background: '#fff',
            border: '1px solid var(--n-200)',
            borderRadius: 8,
          }}>
            <div style={{
              display: 'flex', alignItems: 'center', gap: 10,
              padding: '12px 20px',
              borderBottom: '1px solid var(--n-200)',
              background: 'var(--n-050)', borderRadius: '8px 8px 0 0',
            }}>
              <div style={{
                fontFamily: 'Inter', fontSize: 11, fontWeight: 700, letterSpacing: '0.06em',
                color: 'var(--n-500)', textTransform: 'uppercase',
              }}>변경 이력</div>
              <div style={{ fontSize: 11, color: 'var(--n-500)' }}>최근 5건</div>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="var(--n-500)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ marginLeft: 'auto' }}>
                <polyline points="6 9 12 15 18 9"/>
              </svg>
            </div>
            <div style={{ padding: '4px 20px 12px' }}>
              <HistoryRow
                when="2026-03-22 14:08" who="admin.park@kare.co.kr"
                change={['비율 8.0% → 10.0%']} memo="CNT-2026-0312 · 연간 협정 갱신"
              />
              <HistoryRow
                when="2025-11-10 09:47" who="admin.kim@kare.co.kr"
                change={['수동 OFF → ON']} memo="현장 운영 이슈 대응 · 긴급 승인"
              />
              <HistoryRow
                when="2025-09-02 11:20" who="admin.park@kare.co.kr"
                change={['비율 5.0% → 8.0%']} memo="상반기 정산 결과 반영"
              />
              <HistoryRow
                when="2025-05-18 16:33" who="admin.lee@kare.co.kr"
                change={['비율 0.0% → 5.0%']} memo="본사 계약서 부속합의"
              />
              <HistoryRow
                when="2024-01-14 10:00" who="system"
                change={['초기 등록']} memo="파트너 등록 (기본값)"
              />
            </div>
          </div>
        </div>
        <FeatFooter canSave={canSave}/>
      </Modal>
      {isConfirm && <FeatConfirmDialog/>}
    </>
  );
};

const numBtn = {
  width: 22, height: 16,
  background: '#fff', border: '1px solid var(--n-200)',
  borderRadius: 3, cursor: 'pointer',
  color: 'var(--n-500)', fontSize: 8,
  display: 'grid', placeItems: 'center',
};

const FeatureSettingsFrame = ({ variant }) => (
  <AdminLayout activeId="member">
    <div style={{ filter: 'blur(1.5px)', pointerEvents: 'none', opacity: 0.9 }}>
      <PartnerListPage variant="normal"/>
    </div>
    <FeatureSettingsModal variant={variant}/>
  </AdminLayout>
);

Object.assign(window, { FeatureSettingsModal, FeatureSettingsFrame });
