// ─── 설정: 색상 추가/수정/삭제 ────────────────────
function SettingsSheet({ colors, overrides, onColorsChange, onDeleteColor, onClose }) {
  const [drafts, setDrafts] = useState((colors || []).map(c => ({ ...c })));
  const [deletedIds, setDeletedIds] = useState([]);
  useEffect(() => {
    setDrafts((colors || []).map(c => ({ ...c })));
    setDeletedIds([]);
  }, [colors]);

  // drafts 변경 시 Lucide 아이콘 즉시 초기화
  useEffect(() => { if (window.lucide) window.lucide.createIcons(); }, [drafts]);

  const handleHexChange = (idx, hex) => {
    setDrafts(prev => prev.map((c, i) => i === idx ? { ...c, hex } : c));
  };
  const handleLabelChange = (idx, label) => {
    setDrafts(prev => prev.map((c, i) => i === idx ? { ...c, label } : c));
  };
  const handleAdd = () => {
    const id = 'c_' + Date.now();
    setDrafts(prev => [...prev, { id, label: '새 색상', hex: '#888888' }]);
  };
  const handleDelete = (idx) => {
    const c = drafts[idx];
    const affectedCount = Object.values(overrides || {}).filter(v => v.color === c.id).length;
    const msg = affectedCount > 0
      ? `"${c.label}" 색상을 삭제하시겠습니까?\n이 색상이 지정된 필지 ${affectedCount}개가 색상 없음으로 변경됩니다.`
      : `"${c.label}" 색상을 삭제하시겠습니까?`;
    if (!window.confirm(msg)) return;
    setDeletedIds(prev => [...prev, c.id]);
    setDrafts(prev => prev.filter((_, i) => i !== idx));
  };
  const handleSave = () => {
    deletedIds.forEach(id => onDeleteColor(id));
    onColorsChange(drafts.filter(c => c.label && c.label.trim()));
    onClose();
  };
  const handleReset = () => {
    setDrafts(COLORS.map(c => ({ id: c.id, label: c.defaultLabel, hex: c.hex })));
    setDeletedIds([]);
  };

  return (
    <BottomSheet onClose={onClose}>
      <div style={appStyles.sheetHeader}>
        <div style={appStyles.sheetMeta}>설정</div>
        <div style={{ fontSize: 18, fontWeight: 700, color: '#1A1814' }}>색상 설정</div>
        <div style={appStyles.subMeta}>색상 이름과 색상값을 편집하고 새 색상을 추가할 수 있습니다.</div>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {drafts.map((c, idx) => (
          <div key={c.id} style={appStyles.colorEditRow}>
            <input
              type="color"
              value={c.hex}
              onChange={(e) => handleHexChange(idx, e.target.value)}
              style={{
                width: 32, height: 32, borderRadius: 8, border: '1px solid #E4E2DA',
                padding: 2, cursor: 'pointer', background: 'none', flexShrink: 0,
              }}
            />
            <input
              value={c.label}
              placeholder="색상 이름"
              onChange={(e) => handleLabelChange(idx, e.target.value)}
              style={appStyles.colorEditInput}
              maxLength={12}
            />
            <button
              style={{
                flexShrink: 0, width: 28, height: 28,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                background: 'none', border: 'none', cursor: 'pointer',
                color: '#C8392E', borderRadius: 6, padding: 0,
              }}
              onClick={() => handleDelete(idx)}
              aria-label="삭제"
            >
              <i data-lucide="trash-2" style={{ width: 14, height: 14 }}></i>
            </button>
          </div>
        ))}
      </div>

      <button style={appStyles.recipeAddBtn} onClick={handleAdd}>
        + 색상 추가
      </button>

      <div style={{ display: 'flex', gap: 8 }}>
        <button style={{ ...appStyles.closeBtn, flex: 1 }} onClick={handleReset}>기본값</button>
        <button style={{
          ...appStyles.closeBtn, flex: 2,
          background: '#2F7D4F', color: '#FFFFFF', border: '1px solid #2F7D4F',
        }} onClick={handleSave}>저장</button>
      </div>
    </BottomSheet>
  );
}
