// ── FormSteps.jsx ──────────────────────────────────────────────
// All 7 step components for the CIQ form with premium aesthetic

// ── Shared field components ─────────────────────────────────────
function Field({ label, required, hint, children }) {
  return (
    <div className="mb-4">
      <label className="form-label">
        {label}{required && <span style={{ color: '#ef4444', marginLeft: '4px' }}>*</span>}
      </label>
      {hint && <p className="form-hint">{hint}</p>}
      {children}
    </div>
  );
}

function Input({ value, onChange, placeholder, type = 'text', disabled }) {
  return (
    <input
      type={type}
      value={value || ''}
      onChange={e => onChange(e.target.value)}
      placeholder={placeholder}
      disabled={disabled}
      className="form-control"
    />
  );
}

function Select({ value, onChange, options, placeholder }) {
  return (
    <select
      value={value || ''}
      onChange={e => onChange(e.target.value)}
      className="form-control"
      style={{ color: value ? 'inherit' : '#94a3b8' }}
    >
      {placeholder && <option value="" disabled hidden>{placeholder}</option>}
      {options.map(o => <option key={o.value || o} value={o.value || o} style={{ color: '#0f172a' }}>{o.label || o}</option>)}
    </select>
  );
}

function PortInput({ value, onChange, options, placeholder, listId }) {
  return (
    <>
      <input
        list={listId}
        value={value || ''}
        onChange={e => onChange(e.target.value)}
        placeholder={placeholder}
        className="form-control"
      />
      <datalist id={listId}>
        {options.map(o => <option key={o} value={o} />)}
      </datalist>
    </>
  );
}

function Row({ children }) {
  return (
    <div className="grid grid-cols-2">
      {children}
    </div>
  );
}

function SectionTitle({ children }) {
  return (
    <h3 style={{ fontSize: '1rem', fontWeight: '700', color: 'var(--text-primary)', marginTop: '2rem', marginBottom: '1rem', paddingBottom: '0.5rem', borderBottom: '1px solid var(--border)' }}>
      {children}
    </h3>
  );
}

function defaultCrewLegs(legs = {}) {
  const hasKoreaToJapan = typeof legs.koreaToJapan === 'boolean';
  const hasJapanToKorea = typeof legs.japanToKorea === 'boolean';
  return {
    koreaToJapan: hasKoreaToJapan ? legs.koreaToJapan : true,
    japanToKorea: hasJapanToKorea ? legs.japanToKorea : true,
  };
}

function createCrewMember() {
  return { legs: defaultCrewLegs() };
}

// ── Step 1: 신청자 정보 ─────────────────────────────────────────
function Step1({ data, set }) {
  const f = (k) => (v) => set({ ...data, [k]: v });
  return (
    <div className="animate-fade-in">
      <Row>
        <Field label="신청자 성명" required>
          <Input value={data.name} onChange={f('name')} placeholder="홍길동" />
        </Field>
        <Field label="연락처" required>
          <Input value={data.phone} onChange={f('phone')} placeholder="010-0000-0000" />
        </Field>
      </Row>
      <Row>
        <Field label="이메일" required hint="접수 확인 메일이 발송됩니다">
          <Input value={data.email} onChange={f('email')} type="email" placeholder="example@email.com" />
        </Field>
        <Field label="신청자 구분" required>
          <Select value={data.role} onChange={f('role')} placeholder="선택하세요"
            options={[
              { value: 'owner', label: '선주' },
              { value: 'captain', label: '선장' },
              { value: 'agent', label: '대리인' },
              { value: 'crew', label: '승선자' },
            ]} />
        </Field>
      </Row>
      <Field label="문의사항 / 특이사항" hint="CIQ 관련 추가 전달 사항이 있으면 입력해 주세요">
        <textarea
          value={data.memo || ''}
          onChange={e => set({ ...data, memo: e.target.value })}
          placeholder="예: 일정이 유동적입니다 / 승선자 중 미성년자 포함"
          rows={4}
          className="form-control"
          style={{ resize: 'vertical' }}
        />
      </Field>
    </div>
  );
}

// ── Step 2: 항해 일정 ──────────────────────────────────────────
function Step2({ data, set }) {
  const f = (k) => (v) => set({ ...data, [k]: v });
  return (
    <div className="animate-fade-in">
      <SectionTitle>🇰🇷 한국 출항</SectionTitle>
      <Row>
        <Field label="출항 항구" required>
          <PortInput value={data.departPort} onChange={f('departPort')} placeholder="선택 또는 직접 입력" listId="korea-depart-ports"
            options={['부산항','거제도','통영','여수','마산','진해','울산','포항']} />
        </Field>
        <Field label="예정 출항일" required>
          <Input value={data.departDate} onChange={f('departDate')} type="date" />
        </Field>
        <Field label="예정 출항 시각" required>
          <Input value={data.departTime} onChange={f('departTime')} type="time" />
        </Field>
      </Row>
      <Row>
        <Field label="출항 CIQ 장소" required>
          <Input value={data.departCiqPlace} onChange={f('departCiqPlace')} placeholder="예: 통영항 금호마리나" />
        </Field>
        <Field label="출항 선석/계선장소" required>
          <Input value={data.departBerth} onChange={f('departBerth')} placeholder="예: 금호마리나 A선석" />
        </Field>
      </Row>

      <SectionTitle>🇯🇵 일본 입항</SectionTitle>
      <Row>
        <Field label="입항 항구" required>
          <PortInput value={data.arrivePort} onChange={f('arrivePort')} placeholder="선택 또는 직접 입력" listId="japan-arrive-ports"
            options={['쓰시마(이즈하라)','쓰시마(히타카쓰)','후쿠오카','나가사키','사세보','시모노세키','고베','오사카','도쿄']} />
        </Field>
        <Field label="예정 입항일" required>
          <Input value={data.arriveDate} onChange={f('arriveDate')} type="date" />
        </Field>
        <Field label="예정 입항 시각">
          <Input value={data.arriveTime} onChange={f('arriveTime')} type="time" />
        </Field>
      </Row>

      <SectionTitle>🇯🇵 일본 출항 (귀항 예정)</SectionTitle>
      <Row>
        <Field label="출항 항구" required>
          <PortInput value={data.returnDepartPort} onChange={f('returnDepartPort')} placeholder="미정 / 선택 또는 직접 입력" listId="japan-return-depart-ports"
            options={['미정','쓰시마(이즈하라)','쓰시마(히타카쓰)','후쿠오카','나가사키','사세보','시모노세키','고베','오사카','도쿄']} />
        </Field>
        <Field label="예정 출항일" required>
          <Input value={data.returnDepartDate} onChange={f('returnDepartDate')} type="date" />
        </Field>
        <Field label="예정 출항 시각" required>
          <Input value={data.returnDepartTime} onChange={f('returnDepartTime')} type="time" />
        </Field>
      </Row>

      <SectionTitle>🇰🇷 한국 입항 (귀항)</SectionTitle>
      <Row>
        <Field label="입항 항구" required>
          <PortInput value={data.returnArrivePort} onChange={f('returnArrivePort')} placeholder="미정 / 선택 또는 직접 입력" listId="korea-return-arrive-ports"
            options={['미정','부산항','거제도','통영','여수','마산','진해','울산','포항']} />
        </Field>
        <Field label="예정 입항일" required>
          <Input value={data.returnArriveDate} onChange={f('returnArriveDate')} type="date" />
        </Field>
        <Field label="예정 입항 시각" required>
          <Input value={data.returnArriveTime} onChange={f('returnArriveTime')} type="time" />
        </Field>
      </Row>
      <Row>
        <Field label="입항 CIQ 장소" required>
          <Input value={data.returnCiqPlace} onChange={f('returnCiqPlace')} placeholder="예: 통영항 금호마리나" />
        </Field>
        <Field label="입항 선석/계선장소" required>
          <Input value={data.returnBerth} onChange={f('returnBerth')} placeholder="예: 금호마리나 A선석" />
        </Field>
      </Row>

      <div className="mt-8">
        <Field label="일본 계류 예정 위치">
          <Input value={data.japanBerth} onChange={f('japanBerth')} placeholder="예: Hitakatsu Port / Fukuoka Marina" />
        </Field>
        <Field label="항해 목적" required>
          <Select value={data.purpose} onChange={f('purpose')} placeholder="선택하세요"
            options={[
              { value: 'leisure', label: '레저 / 크루징' },
              { value: 'race', label: '레이스 / 대회 참가' },
              { value: 'delivery', label: '선박 이동 (딜리버리)' },
              { value: 'other', label: '기타' },
            ]} />
        </Field>
      </div>
    </div>
  );
}

// ── Step 3: 선박 정보 ──────────────────────────────────────────
function Step3({ data, set }) {
  const f = (k) => (v) => set({ ...data, [k]: v });
  return (
    <div className="animate-fade-in">
      <Row>
        <Field label="선박명 (한글)" required>
          <Input value={data.vesselNameKo} onChange={f('vesselNameKo')} placeholder="예: 한라호" />
        </Field>
        <Field label="선박명 (영문)" required>
          <Input value={data.vesselNameEn} onChange={f('vesselNameEn')} placeholder="예: HALLA" />
        </Field>
      </Row>
      <Row>
        <Field label="선박 종류" required>
          <Select value={data.vesselType} onChange={f('vesselType')} placeholder="선택"
            options={['세일요트','모터요트','모터보트','카타마란','기타']} />
        </Field>
        <Field label="선적항" required>
          <Input value={data.homePort} onChange={f('homePort')} placeholder="예: 부산" />
        </Field>
      </Row>
      <Row>
        <Field label="선박 국적" required>
          <Select value={data.flag} onChange={f('flag')} placeholder="선택"
            options={['대한민국','일본','미국','영국','기타']} />
        </Field>
        <Field label="선박 등록번호" required>
          <Input value={data.regNum} onChange={f('regNum')} placeholder="예: 12-가-1234" />
        </Field>
      </Row>
      <Row>
        <Field label="전장 (LOA, m)" required>
          <Input value={data.loa} onChange={f('loa')} placeholder="예: 12.5" />
        </Field>
        <Field label="폭 (m)">
          <Input value={data.beam} onChange={f('beam')} placeholder="예: 3.8" />
        </Field>
        <Field label="깊이 (m)">
          <Input value={data.depth} onChange={f('depth')} placeholder="예: 2.1" />
        </Field>
        <Field label="총톤수 (GT)">
          <Input value={data.gt} onChange={f('gt')} placeholder="예: 8.5" />
        </Field>
        <Field label="순톤수 (NT)">
          <Input value={data.nt} onChange={f('nt')} placeholder="예: 8.5" />
        </Field>
        <Field label="엔진 마력 (HP)">
          <Input value={data.hp} onChange={f('hp')} placeholder="예: 55" />
        </Field>
      </Row>
      <Row>
        <Field label="콜사인 (Call Sign)">
          <Input value={data.callSign} onChange={f('callSign')} placeholder="예: HLXX" />
        </Field>
        <Field label="MMSI">
          <Input value={data.mmsi} onChange={f('mmsi')} placeholder="예: 440XXXXXXX" />
        </Field>
      </Row>
      <SectionTitle>연료·검역 참고 정보</SectionTitle>
      <Row>
        <Field label="연료탱크 용량 (kl)">
          <Input value={data.fuelTankKl} onChange={f('fuelTankKl')} placeholder="예: 0.195" />
        </Field>
        <Field label="한국 출항 시 연료 잔량 (L)">
          <Input value={data.fuelDepartureL} onChange={f('fuelDepartureL')} placeholder="예: 180" />
        </Field>
        <Field label="한국 입항 시 예상 연료 잔량 (L)">
          <Input value={data.fuelArrivalL} onChange={f('fuelArrivalL')} placeholder="예: 100" />
        </Field>
      </Row>
      <Row>
        <Field label="검역 검사일">
          <Input value={data.quarantineInspectionDate} onChange={f('quarantineInspectionDate')} placeholder="예: 2026年 05月 11日" />
        </Field>
        <Field label="최근 일본 입항 횟수">
          <Input value={data.previousJapanEntriesCount} onChange={f('previousJapanEntriesCount')} placeholder="예: 0" />
        </Field>
      </Row>
      <Field label="선박 설명 / 특이사항" hint="색상, 외형 특징 등 CIQ 신고에 도움되는 정보">
        <textarea
          value={data.vesselMemo || ''}
          onChange={e => set({ ...data, vesselMemo: e.target.value })}
          rows={3}
          placeholder="예: 흰색 선체, 붉은 줄무늬, 돛대 2개"
          className="form-control"
          style={{ resize: 'vertical' }}
        />
      </Field>
    </div>
  );
}

// ── Step 4: 선주/선장 정보 ─────────────────────────────────────
function Step4({ data, set }) {
  const f = (k) => (v) => set({ ...data, [k]: v });
  const fo = (k) => (v) => set({ ...data, owner: { ...data.owner, [k]: v } });
  return (
    <div className="animate-fade-in">
      <SectionTitle>선장 정보</SectionTitle>
      <Row>
        <Field label="선장 성명 (한글)" required>
          <Input value={data.captainNameKo} onChange={f('captainNameKo')} placeholder="홍길동" />
        </Field>
        <Field label="선장 성명 (영문, 여권 기준)" required>
          <Input value={data.captainNameEn} onChange={f('captainNameEn')} placeholder="HONG GILDONG" />
        </Field>
      </Row>
      <Row>
        <Field label="여권번호" required hint="여권번호는 제출 자료 정리 목적으로만 사용됩니다">
          <Input value={data.captainPassport} onChange={f('captainPassport')} placeholder="M12345678" />
        </Field>
        <Field label="여권 만료일" required>
          <Input value={data.captainPassportExpiry} onChange={f('captainPassportExpiry')} type="date" />
        </Field>
      </Row>
      <Row>
        <Field label="국적" required>
          <Select value={data.captainNationality} onChange={f('captainNationality')} placeholder="선택"
            options={['대한민국','일본','미국','기타']} />
        </Field>
        <Field label="생년월일" required>
          <Input value={data.captainDob} onChange={f('captainDob')} type="date" />
        </Field>
        <Field label="성별" required>
          <Select value={data.captainSex} onChange={f('captainSex')} placeholder="선택"
            options={[
              { value: 'M', label: '남성' },
              { value: 'F', label: '여성' },
            ]} />
        </Field>
      </Row>
      <Row>
        <Field label="연락처 (위성/위급)">
          <Input value={data.captainPhone} onChange={f('captainPhone')} placeholder="010-0000-0000" />
        </Field>
        <Field label="선장 자격증 종류">
          <Select value={data.licenseType} onChange={f('licenseType')} placeholder="선택"
            options={['요트 조종면허 1급','요트 조종면허 2급','동력수상레저기구 1급','동력수상레저기구 2급','기타']} />
        </Field>
      </Row>
      <Row>
        <Field label="선장 주소">
          <Input value={data.captainAddressKo} onChange={f('captainAddressKo')} placeholder="국문 주소" />
        </Field>
        <Field label="선장 영문 주소">
          <Input value={data.captainAddressEn} onChange={f('captainAddressEn')} placeholder="영문 주소" />
        </Field>
      </Row>

      <SectionTitle>선주 정보 <span style={{ fontWeight: '400', color: 'var(--text-muted)', fontSize: '0.875rem' }}>(선장과 다른 경우)</span></SectionTitle>
      <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '1rem' }}>
        <input type="checkbox"
          id="sameAsCaptain"
          checked={data.ownerSameAsCaptain || false}
          onChange={e => set({ ...data, ownerSameAsCaptain: e.target.checked })}
          style={{ width: '18px', height: '18px', cursor: 'pointer', accentColor: 'var(--primary)' }}
        />
        <label htmlFor="sameAsCaptain" style={{ fontSize: '0.9375rem', color: 'var(--text-primary)', cursor: 'pointer', fontWeight: '500' }}>선주 = 선장 (동일인)</label>
      </div>

      {!data.ownerSameAsCaptain && (
        <div className="animate-fade-in" style={{ padding: '1.5rem', background: '#f8fafc', borderRadius: 'var(--radius-lg)', border: '1px solid var(--border)' }}>
          <Row>
            <Field label="선주 성명 (한글)">
              <Input value={data.owner?.nameKo} onChange={fo('nameKo')} placeholder="홍길동" />
            </Field>
            <Field label="선주 성명 (영문)">
              <Input value={data.owner?.nameEn} onChange={fo('nameEn')} placeholder="HONG GILDONG" />
            </Field>
          </Row>
          <Row>
            <Field label="연락처">
              <Input value={data.owner?.phone} onChange={fo('phone')} placeholder="010-0000-0000" />
            </Field>
            <Field label="이메일">
              <Input value={data.owner?.email} onChange={fo('email')} type="email" placeholder="example@email.com" />
            </Field>
          </Row>
          <Row>
            <Field label="생년월일 또는 법인번호">
              <Input value={data.owner?.birthOrRegistrationNo} onChange={fo('birthOrRegistrationNo')} placeholder="생년월일 또는 법인등록번호" />
            </Field>
            <Field label="선주 주소">
              <Input value={data.owner?.addressKo} onChange={fo('addressKo')} placeholder="국문 주소" />
            </Field>
            <Field label="선주 영문 주소">
              <Input value={data.owner?.addressEn} onChange={fo('addressEn')} placeholder="영문 주소" />
            </Field>
          </Row>
        </div>
      )}
    </div>
  );
}

// ── Step 5: 승선자 정보 ─────────────────────────────────────────
function Step5({ data, set }) {
  const crew = (data.crew && data.crew.length ? data.crew : [createCrewMember()])
    .map(c => ({ ...c, legs: defaultCrewLegs(c.legs) }));

  function updateCrew(idx, key, val) {
    const next = crew.map((c, i) => i === idx ? { ...c, [key]: val } : c);
    set({ ...data, crew: next });
  }

  function updateCrewLeg(idx, key, checked) {
    const next = crew.map((c, i) => {
      if (i !== idx) return c;
      const currentLegs = defaultCrewLegs(c.legs);
      const nextLegs = { ...currentLegs, [key]: checked };
      if (!nextLegs.koreaToJapan && !nextLegs.japanToKorea) return c;
      return { ...c, legs: nextLegs };
    });
    set({ ...data, crew: next });
  }

  function addCrew() {
    set({ ...data, crew: [...crew, createCrewMember()] });
  }

  function removeCrew(idx) {
    set({ ...data, crew: crew.filter((_, i) => i !== idx) });
  }

  return (
    <div className="animate-fade-in">
      <p style={{ fontSize: '0.875rem', color: 'var(--text-secondary)', marginBottom: '1.5rem' }}>
        선장을 포함한 전 승선자, 즉 선원(승객)을 입력해 주세요. 각 인원이 참가하는 항해 구간을 선택할 수 있습니다.
      </p>
      {crew.map((c, idx) => {
        const legs = defaultCrewLegs(c.legs);
        const legLabel = legs.koreaToJapan && legs.japanToKorea
          ? '한국 ↔ 일본 전체 일정 참가'
          : legs.koreaToJapan
            ? '한국 → 일본만 참가'
            : '일본 → 한국만 참가';
        return (
        <div key={idx} style={{
          background: '#f8fafc', border: '1px solid var(--border)', borderRadius: 'var(--radius-lg)',
          padding: '1.5rem', marginBottom: '1rem', transition: 'all 0.2s ease'
        }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1rem' }}>
            <span style={{ fontWeight: '700', fontSize: '1rem', color: 'var(--text-primary)' }}>승선자 {idx + 1} <span style={{ color: 'var(--text-muted)', fontWeight: '500' }}>(선원(승객))</span></span>
            {crew.length > 1 && (
              <button onClick={() => removeCrew(idx)} style={{
                background: 'none', border: 'none', color: '#ef4444', fontSize: '0.875rem', fontWeight: '600', cursor: 'pointer', padding: '0.25rem 0.5rem'
              }}>삭제</button>
            )}
          </div>
          <Row>
            <Field label="성명 (한글)" required>
              <Input value={c.nameKo} onChange={v => updateCrew(idx, 'nameKo', v)} placeholder="홍길동" />
            </Field>
            <Field label="성명 (영문, 여권 기준)" required>
              <Input value={c.nameEn} onChange={v => updateCrew(idx, 'nameEn', v)} placeholder="HONG GILDONG" />
            </Field>
          </Row>
          <Row>
            <Field label="여권번호" required>
              <Input value={c.passport} onChange={v => updateCrew(idx, 'passport', v)} placeholder="M12345678" />
            </Field>
            <Field label="여권 만료일">
              <Input value={c.passportExpiry} onChange={v => updateCrew(idx, 'passportExpiry', v)} type="date" />
            </Field>
          </Row>
          <Row>
            <Field label="생년월일" required>
              <Input value={c.dob} onChange={v => updateCrew(idx, 'dob', v)} type="date" />
            </Field>
            <Field label="성별" required>
              <Select value={c.sex} onChange={v => updateCrew(idx, 'sex', v)} placeholder="선택"
                options={[
                  { value: 'M', label: '남성' },
                  { value: 'F', label: '여성' },
                ]} />
            </Field>
            <Field label="국적">
              <Select value={c.nationality} onChange={v => updateCrew(idx, 'nationality', v)} placeholder="선택"
                options={['대한민국','일본','미국','기타']} />
            </Field>
          </Row>
          <Row>
            <Field label="연락처">
              <Input value={c.phone} onChange={v => updateCrew(idx, 'phone', v)} placeholder="010-0000-0000" />
            </Field>
            <Field label="주소">
              <Input value={c.address} onChange={v => updateCrew(idx, 'address', v)} placeholder="국문 주소" />
            </Field>
          </Row>
          <Field label="탑승 구간" hint={legLabel}>
            <div style={{ display: 'flex', gap: '0.75rem', flexWrap: 'wrap' }}>
              {[
                { key: 'koreaToJapan', label: '한국 → 일본' },
                { key: 'japanToKorea', label: '일본 → 한국' },
              ].map(option => (
                <label key={option.key} style={{
                  display: 'flex', alignItems: 'center', gap: '0.5rem', minHeight: '44px',
                  padding: '0.75rem 1rem', border: '1px solid var(--border)', borderRadius: 'var(--radius-md)',
                  background: legs[option.key] ? 'white' : '#f8fafc', cursor: 'pointer',
                  color: 'var(--text-primary)', fontWeight: '600', fontSize: '0.875rem'
                }}>
                  <input
                    type="checkbox"
                    checked={legs[option.key]}
                    onChange={e => updateCrewLeg(idx, option.key, e.target.checked)}
                    style={{ width: '16px', height: '16px', accentColor: 'var(--primary)' }}
                  />
                  {option.label}
                </label>
              ))}
            </div>
          </Field>
        </div>
        );
      })}
      <button onClick={addCrew} className="btn" style={{
        width: '100%', background: 'transparent', border: '2px dashed var(--primary)', color: 'var(--primary)',
      }}>
        + 승선자 추가
      </button>
    </div>
  );
}

// ── Step 6: 첨부파일 ───────────────────────────────────────────
function FileUploadItem({ label, required, hint, fileKey, files, setFiles }) {
  const file = files[fileKey];
  const inputRef = React.useRef();

  function handleChange(e) {
    const f = e.target.files[0];
    if (!f) return;
    const allowedTypes = ['image/jpeg', 'image/png', 'image/jpg', 'image/heic', 'image/heif', 'application/pdf'];
    const allowedExtensions = ['jpg', 'jpeg', 'png', 'pdf', 'heic'];
    const extension = f.name.split('.').pop().toLowerCase();
    if (!allowedTypes.includes(f.type) && !allowedExtensions.includes(extension)) {
      alert('JPG, PNG, HEIC, PDF 파일만 업로드 가능합니다.');
      return;
    }
    if (f.size > 10 * 1024 * 1024) {
      alert('파일 크기는 10MB 이하여야 합니다.');
      return;
    }
    const nextTotal = Object.entries(files).reduce((sum, [key, item]) => {
      if (key === fileKey) return sum;
      return sum + (item?.size || 0);
    }, 0) + f.size;
    if (nextTotal > 50 * 1024 * 1024) {
      alert('첨부파일 총 용량은 50MB 이하여야 합니다.');
      return;
    }
    setFiles(prev => ({ ...prev, [fileKey]: { name: f.name, size: f.size, type: f.type, file: f } }));
  }

  function remove() {
    setFiles(prev => { const n = { ...prev }; delete n[fileKey]; return n; });
    if (inputRef.current) inputRef.current.value = '';
  }

  return (
    <div className="mb-4">
      <div className="form-label">
        {label}{required && <span style={{ color: '#ef4444', marginLeft: '4px' }}>*</span>}
      </div>
      {hint && <p className="form-hint">{hint}</p>}
      {file ? (
        <div style={{
          display: 'flex', alignItems: 'center', gap: '1rem',
          background: 'var(--primary-light)', border: '1px solid #bae6fd', borderRadius: 'var(--radius-md)', padding: '0.75rem 1rem'
        }}>
          <span style={{ fontSize: '1.5rem' }}>{file.type === 'application/pdf' ? '📄' : '🖼️'}</span>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: '0.875rem', fontWeight: '600', color: '#0369a1', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{file.name}</div>
            <div style={{ fontSize: '0.75rem', color: '#0284c7' }}>{(file.size / 1024).toFixed(0)} KB</div>
          </div>
          <button onClick={remove} style={{ background: 'none', border: 'none', color: '#0369a1', cursor: 'pointer', fontSize: '1.25rem' }}>✕</button>
        </div>
      ) : (
        <label style={{
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '0.5rem',
          background: '#ffffff', border: '2px dashed #cbd5e1', borderRadius: 'var(--radius-md)',
          padding: '1rem', cursor: 'pointer', color: 'var(--text-secondary)', fontSize: '0.875rem',
          transition: 'all 0.2s', fontWeight: '500'
        }}
        onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--primary)'; e.currentTarget.style.color = 'var(--primary)'; }}
        onMouseLeave={e => { e.currentTarget.style.borderColor = '#cbd5e1'; e.currentTarget.style.color = 'var(--text-secondary)'; }}>
          <span style={{ fontSize: '1.25rem' }}>⊕</span> 파일 선택 (JPG·PNG·HEIC·PDF, 최대 10MB)
          <input ref={inputRef} type="file" accept=".jpg,.jpeg,.png,.heic,.pdf" onChange={handleChange} style={{ display: 'none' }} />
        </label>
      )}
    </div>
  );
}

function Step6({ files, setFiles }) {
  const items = [
    { key: 'passport_all', label: '전 승선자 여권 사본', required: true, hint: '자동 패키징에는 PDF 묶음이 가장 안정적입니다' },
    { key: 'captain_passport', label: '선장 여권 사본', required: true, hint: '일본 운수국·입국관리국 제출 패키지에 사용됩니다' },
    { key: 'captain_license', label: '선장 자격증 사본', required: false, hint: '요트 조종면허 또는 동력수상레저기구 조종면허' },
    { key: 'vessel_reg', label: '선박 등록증 사본', required: true, hint: '선박 원부 또는 등록증명서' },
    { key: 'safety_cert', label: '안전검사증 사본', required: true, hint: '유효기간 확인 필수' },
    { key: 'sscec', label: 'SSCEC (소형선박 안전관리증)', required: false, hint: '해당 선박에 발급된 경우 제출' },
    { key: 'transport_permit', label: '운수국 허가서', required: false, hint: '기존 불개항장 기항 특허 통지서가 있는 경우' },
    { key: 'mooring_map', label: '계류장소 도면', required: false, hint: '일본 해상보안청·항만 제출용 참고자료' },
    { key: 'pow', label: '위임장', required: false, hint: '선주 ≠ 신청자인 경우 필요. 양식 다운로드 후 작성 가능' },
    { key: 'insurance', label: '선박 보험증권', required: false, hint: '일본 입항 일부 항구에서 요구' },
    { key: 'other', label: '기타 서류', required: false, hint: '추가로 제출할 서류가 있으면 업로드' },
  ];

  return (
    <div className="animate-fade-in">
      <div style={{ background: '#fffbeb', border: '1px solid #fcd34d', borderRadius: 'var(--radius-md)', padding: '1rem', marginBottom: '1.5rem', fontSize: '0.875rem', color: '#92400e', display: 'flex', gap: '0.5rem' }}>
        <span style={{ fontSize: '1.25rem' }}>⚠️</span>
        <div style={{ alignSelf: 'center' }}>업로드된 파일은 접수 처리용 서버 저장소에 보관되며, 서류 준비 목적 외 사용되지 않습니다.</div>
      </div>
      {items.map(item => (
        <FileUploadItem key={item.key} fileKey={item.key} {...item} files={files} setFiles={setFiles} />
      ))}
      <div style={{ marginTop: '1.5rem', padding: '1rem', background: '#f0fdf4', border: '1px solid #bbf7d0', borderRadius: 'var(--radius-md)', fontSize: '0.875rem', color: '#15803d', display: 'flex', gap: '0.5rem' }}>
        <span style={{ fontSize: '1.25rem' }}>💡</span>
        <div style={{ alignSelf: 'center' }}>
          위임장 양식이 필요하신 경우 <a href="#" style={{ color: '#15803d', fontWeight: '700', textDecoration: 'underline' }}>여기서 다운로드</a>하여 작성 후 업로드 해주세요.
        </div>
      </div>
    </div>
  );
}

// ── Step 7: 요약 및 제출 ───────────────────────────────────────
function Step7({ summary, consent, setConsent }) {
  const toggle = (key) => (e) => setConsent({ ...consent, [key]: e.target.checked });
  return (
    <div className="animate-fade-in">
      <div style={{ background: '#f8fafc', border: '1px solid var(--border)', borderRadius: 'var(--radius-lg)', padding: '1.5rem' }}>
        <h3 style={{ fontSize: '1rem', fontWeight: '700', color: 'var(--text-primary)', marginBottom: '1rem' }}>제출 내용 요약</h3>
        {summary.map((row, i) => (
          <div key={i} style={{ display: 'flex', justifyContent: 'space-between', padding: '0.5rem 0', borderBottom: i < summary.length - 1 ? '1px solid var(--border)' : 'none', fontSize: '0.875rem' }}>
            <span style={{ color: 'var(--text-secondary)' }}>{row.label}</span>
            <span style={{ color: 'var(--text-primary)', fontWeight: '600', textAlign: 'right', maxWidth: '55%' }}>{row.value || '—'}</span>
          </div>
        ))}
      </div>
      <div style={{ marginTop: '1.5rem', display: 'grid', gap: '0.75rem' }}>
        {[
          ['privacy', '개인정보 수집·이용에 동의합니다.'],
          ['sensitive', '여권번호, 생년월일 등 CIQ 서류 작성에 필요한 민감정보 처리에 동의합니다.'],
          ['ciq', '입력 자료를 CIQ 서류 준비와 기관별 제출자료 정리에 사용하는 데 동의합니다.'],
        ].map(([key, label]) => (
          <label key={key} style={{
            display: 'flex', gap: '0.75rem', alignItems: 'flex-start',
            padding: '0.875rem 1rem', border: '1px solid var(--border)', borderRadius: 'var(--radius-md)',
            background: consent?.[key] ? '#f0fdf4' : '#ffffff', fontSize: '0.875rem',
            color: 'var(--text-primary)', fontWeight: '600', lineHeight: 1.5
          }}>
            <input type="checkbox" checked={!!consent?.[key]} onChange={toggle(key)}
              style={{ width: '18px', height: '18px', marginTop: '1px', accentColor: 'var(--primary)' }} />
            {label}
          </label>
        ))}
      </div>
    </div>
  );
}

// Export all to window
Object.assign(window, { Step1, Step2, Step3, Step4, Step5, Step6, Step7, Field, Input, Select, PortInput, Row, SectionTitle });
