// ─── 바텀시트: 지번 선택 ─────────────────────
function ParcelSheet({ parcel, landInfo, onFetchLandInfo, override, colors, colorById, colorLabels, areaUnit, onAreaUnitChange, onChange, onClose, isWide }) {
  const openedAtRef = useRef(Date.now());

  const colorList = colors || COLORS.map(c => ({ id: c.id, label: c.defaultLabel, hex: c.hex }));
  const colorMap  = colorById || COLOR_BY_ID;

  const [draft, setDraft] = useState({
    name:   (override && override.name)   || '',
    memo:   (override && override.memo)   || '',
    color:  (override && override.color)  || null,
    style:  (override && override.style)  || 'fill',
    pinned: (override && override.pinned) || false,
    icon:   (override && override.icon)   || '',
  });

  useEffect(() => {
    setDraft({
      name:   (override && override.name)   || '',
      memo:   (override && override.memo)   || '',
      color:  (override && override.color)  || null,
      style:  (override && override.style)  || 'fill',
      pinned: (override && override.pinned) || false,
      icon:   (override && override.icon)   || '',
    });
  }, [parcel.id]);

  const handleSave = () => {
    const patch = {
      name:   draft.name.trim(),
      memo:   draft.memo.trim(),
      color:  draft.color,
      style:  draft.color ? draft.style : null,
      pinned: draft.pinned,
      icon:   draft.pinned ? draft.icon : '',
    };
    onChange(patch);
    onClose();
  };

  const content = (
    <React.Fragment>
      <div style={appStyles.sheetHeader}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={appStyles.sheetMeta}>지번</div>
          <button style={appStyles.closeX} onClick={onClose} aria-label="닫기">
            <i data-lucide="x" style={{ width: 18, height: 18 }}></i>
          </button>
        </div>
        <input
          value={draft.name}
          onChange={(e) => setDraft(d => ({ ...d, name: e.target.value }))}
          placeholder={parcel.jibun || '이름 입력'}
          style={appStyles.nameInput}
        />
        {draft.name.trim() && (
          <div style={appStyles.subMeta}>
            기본 지번: <span style={{ fontFamily: 'IBM Plex Mono, monospace' }}>{parcel.jibun}</span>
          </div>
        )}
        {parcel.area != null && (
          <div style={appStyles.areaRow}>
            <span style={appStyles.areaValue}>{convertArea(parcel.area, areaUnit)}</span>
            <div style={appStyles.unitToggle}>
              {AREA_UNITS.map(u => (
                <button
                  key={u.id}
                  style={{ ...appStyles.unitBtn, ...(areaUnit === u.id ? appStyles.unitBtnActive : {}) }}
                  onClick={() => onAreaUnitChange(u.id)}
                >
                  {u.label}
                </button>
              ))}
            </div>
          </div>
        )}
      </div>

      {landInfo?.pnu && (
        <div style={appStyles.section}>
          <div style={appStyles.sectionLabel}>토지임야 정보</div>
          {landInfo.vworld_fetched_at ? (
            <div style={appStyles.landInfoCard}>
              {landInfo.lndcgr_code_nm && (
                <div style={appStyles.landInfoRow}>
                  <span style={appStyles.landInfoKey}>지목</span>
                  <span style={appStyles.landInfoVal}>{landInfo.lndcgr_code_nm}</span>
                </div>
              )}
              {landInfo.posesn_se_code_nm && (
                <div style={appStyles.landInfoRow}>
                  <span style={appStyles.landInfoKey}>소유구분</span>
                  <span style={appStyles.landInfoVal}>{landInfo.posesn_se_code_nm}</span>
                </div>
              )}
              {landInfo.cnrs_psn_co != null && landInfo.cnrs_psn_co > 1 && (
                <div style={appStyles.landInfoRow}>
                  <span style={appStyles.landInfoKey}>공유인수</span>
                  <span style={appStyles.landInfoVal}>{landInfo.cnrs_psn_co}명</span>
                </div>
              )}
            </div>
          ) : (
            <button style={appStyles.landInfoFetchBtn} onClick={onFetchLandInfo}>
              토지임야 조회
            </button>
          )}
        </div>
      )}

      <div style={appStyles.section}>
        <div style={appStyles.sectionLabel}>메모</div>
        <textarea
          value={draft.memo}
          onChange={(e) => setDraft(d => ({ ...d, memo: e.target.value }))}
          placeholder="이 필지에 대한 메모를 입력하세요"
          style={appStyles.memoInput}
          rows={3}
        />
      </div>

      <div style={appStyles.section}>
        <div style={appStyles.sectionLabel}>표시 방식</div>
        <div style={appStyles.styleRow}>
          {STYLE_OPTIONS.map(s => {
            const active = draft.style === s.id;
            const disabled = !draft.color;
            const colorHex = (draft.color && colorMap[draft.color]) ? colorMap[draft.color].hex : '#C9C4B6';
            return (
              <button
                key={s.id}
                disabled={disabled}
                style={{
                  ...appStyles.styleBtn,
                  ...(active ? appStyles.styleBtnActive : {}),
                  ...(disabled ? appStyles.styleBtnDisabled : {}),
                }}
                onClick={() => setDraft(d => ({ ...d, style: s.id }))}
              >
                <StylePreview style={s.id} color={colorHex} active={active}/>
                <span style={appStyles.styleLabel}>{s.label}</span>
              </button>
            );
          })}
        </div>
      </div>

      <div style={appStyles.section}>
        <div style={appStyles.sectionLabel}>색상</div>
        <div style={appStyles.swatchGrid}>
          <button
            style={{
              ...appStyles.swatch,
              ...(draft.color == null ? appStyles.swatchActive : {}),
            }}
            onClick={() => setDraft(d => ({ ...d, color: null }))}
          >
            <div style={appStyles.swatchClear}>
              <i data-lucide="x" style={{ width: 16, height: 16, color: '#8E8B82' }}></i>
            </div>
            <span style={appStyles.swatchLabel}>없음</span>
          </button>
          {colorList.map(c => {
            const active = draft.color === c.id;
            return (
              <button
                key={c.id}
                style={{
                  ...appStyles.swatch,
                  ...(active ? appStyles.swatchActive : {}),
                }}
                onClick={() => setDraft(d => ({ ...d, color: c.id }))}
              >
                <div style={{
                  ...appStyles.swatchChip,
                  background: hexA(c.hex, 0.55),
                  borderColor: c.hex,
                }}></div>
                <span style={appStyles.swatchLabel}>{c.label}</span>
              </button>
            );
          })}
        </div>
      </div>

      {/* 고정 필지 섹션 */}
      <div style={appStyles.section}>
        <div style={appStyles.sectionLabel}>고정 필지</div>
        <button
          style={{
            ...appStyles.colorEditRow,
            cursor: 'pointer', fontFamily: 'inherit', width: '100%', textAlign: 'left',
            border: draft.pinned ? '1.5px solid #2F7D4F' : '1px solid #E4E2DA',
            background: draft.pinned ? 'rgba(47,125,79,0.04)' : '#FBFAF6',
            justifyContent: 'space-between',
          }}
          onClick={() => setDraft(d => ({ ...d, pinned: !d.pinned, icon: !d.pinned ? d.icon : '' }))}
        >
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <span style={{ fontSize: 20 }}>📌</span>
            <div>
              <div style={{ fontSize: 14, fontWeight: 600, color: '#1A1814' }}>
                {draft.pinned ? '고정 켜짐' : '고정 꺼짐'}
              </div>
              <div style={{ fontSize: 11, color: '#8E8B82', marginTop: 1 }}>
                초기화 시 색상·이름·아이콘 보호
              </div>
            </div>
          </div>
          <div style={{
            width: 44, height: 24, borderRadius: 12,
            background: draft.pinned ? '#2F7D4F' : '#D4D0C5',
            position: 'relative', flexShrink: 0,
          }}>
            <div style={{
              width: 18, height: 18, borderRadius: 999, background: '#FFFFFF',
              position: 'absolute', top: 3,
              left: draft.pinned ? 23 : 3,
              boxShadow: '0 1px 3px rgba(0,0,0,0.2)',
            }}></div>
          </div>
        </button>

        {draft.pinned && (
          <div style={{ marginTop: 4 }}>
            <div style={{ fontSize: 11, color: '#8E8B82', marginBottom: 8 }}>
              아이콘 선택{draft.icon ? ` (현재: ${draft.icon})` : ''}
            </div>
            {PIN_ICON_CATEGORIES.map(cat => (
              <div key={cat.label} style={{ marginBottom: 10 }}>
                <div style={{ fontSize: 11, color: '#8E8B82', marginBottom: 4 }}>{cat.label}</div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                  {cat.icons.map(icon => (
                    <button
                      key={icon}
                      style={{
                        width: 36, height: 36, fontSize: 20, cursor: 'pointer',
                        borderRadius: 8, padding: 0,
                        border: draft.icon === icon ? '2px solid #2F7D4F' : '1px solid #E4E2DA',
                        background: draft.icon === icon ? 'rgba(47,125,79,0.08)' : '#FFFFFF',
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                      }}
                      onClick={() => setDraft(d => ({ ...d, icon: d.icon === icon ? '' : icon }))}
                    >
                      {icon}
                    </button>
                  ))}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      <button style={appStyles.saveBtn} onClick={handleSave}>저장</button>
    </React.Fragment>
  );

  if (isWide) {
    return (
      <div style={appStyles.sheetPanel}>
        {content}
      </div>
    );
  }

  return (
    <BottomSheet onClose={() => { if (Date.now() - openedAtRef.current > 500) onClose(); }}>
      {content}
    </BottomSheet>
  );
}
