function areaInUnit(m2, unitLabel) {
  if (unitLabel === '평') return m2 * 0.3025;
  if (unitLabel === 'a')  return m2 / 100;
  if (unitLabel === 'ha') return m2 / 10000;
  return m2;
}

// ─── 자동 계산기 결과 시트 ───────────────────
function CalculatorResultSheet({ parcel, areaM2, group, groupAreaM2, recipes, areaUnit, onAreaUnitChange, onCalcModeChange, onClose }) {
  const hasGroup = !!group;
  const [calcMode, setCalcMode] = React.useState(() => hasGroup ? 'group' : 'individual');

  const effectiveAreaM2 = (hasGroup && calcMode === 'group') ? groupAreaM2 : areaM2;

  React.useEffect(() => {
    if (hasGroup && onCalcModeChange) onCalcModeChange('group');
  }, []);

  function switchCalcMode(mode) {
    setCalcMode(mode);
    if (onCalcModeChange) onCalcModeChange(mode);
  }

  const headerTitle = (hasGroup && calcMode === 'group')
    ? (group.name || `그룹 (${(group.parcels || []).length}필지)`)
    : parcel.jibun;

  const memberCount = hasGroup ? (group.parcels || []).length : 0;

  return (
    <BottomSheet onClose={onClose}>
      <div style={appStyles.sheetHeader}>
        <div style={appStyles.sheetMeta}>자동 계산기</div>

        {hasGroup && (
          <div style={appStyles.calcModeToggle}>
            <button
              style={{ ...appStyles.calcModeBtn, ...(calcMode === 'individual' ? appStyles.calcModeBtnActive : {}) }}
              onClick={() => switchCalcMode('individual')}
            >
              개별 지번
            </button>
            <button
              style={{ ...appStyles.calcModeBtn, ...(calcMode === 'group' ? appStyles.calcModeBtnActive : {}) }}
              onClick={() => switchCalcMode('group')}
            >
              그룹 전체 ({memberCount}필지)
            </button>
          </div>
        )}

        <div style={appStyles.calcResultHeader}>
          <div style={appStyles.calcResultJibun}>{headerTitle}</div>
          {effectiveAreaM2 != null && (
            <div style={appStyles.calcResultArea}>
              <span style={appStyles.calcResultAreaVal}>{convertArea(effectiveAreaM2, 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>
      </div>

      {effectiveAreaM2 == null ? (
        <div style={appStyles.calcNoAreaMsg}>
          {hasGroup && calcMode === 'group'
            ? '그룹 내 필지의 면적 정보가 없습니다.\nVWorld에서 토지 정보를 먼저 조회해주세요.'
            : '이 필지의 면적 정보가 없습니다.\nVWorld에서 토지 정보를 먼저 조회해주세요.'}
        </div>
      ) : recipes.length === 0 ? (
        <div style={appStyles.calcEmptyMsg}>
          설정된 계산 항목이 없습니다.<br />
          자동 계산기 설정에서 항목을 추가하세요.
        </div>
      ) : (
        <div style={appStyles.calcTable}>
          {recipes.map(r => {
            const converted = areaInUnit(effectiveAreaM2, r.baseUnit || '㎡');
            const result = r.baseArea > 0 ? (converted / r.baseArea) * r.amount : 0;
            const formatted = result % 1 === 0
              ? result.toLocaleString('ko')
              : result.toLocaleString('ko', { maximumFractionDigits: 2 });
            return (
              <div key={r.id} style={appStyles.calcTableRow}>
                <span style={appStyles.calcTableName}>{r.name || '(이름 없음)'}</span>
                <span style={appStyles.calcTableVal}>{formatted} {r.amountUnit}</span>
              </div>
            );
          })}
        </div>
      )}
    </BottomSheet>
  );
}
