/* global React, SKG */
const { C, FS, FF, FM, Icon, PrimaryBtn, SecondaryBtn, AppHeader, BottomNav, ConsultFAB } = window.SKG;
const { useState } = React;

// ─────────────────────────────────────────────────────────────
// Screen 11 — Card bulk import (CSV)
// ─────────────────────────────────────────────────────────────
// 4-step wizard:
//   1) template DL / requirements
//   2) file selection / pre-validation
//   3) preview + duplicate policy
//   4) result summary
// All data is dummy; window.alert() simulates side-effects.
// ─────────────────────────────────────────────────────────────

// Dummy preview rows (mix of OK / WARN / ERROR)
const PREVIEW_ROWS = [
  { row: 1,  status: 'OK',    name: '田中 太郎',    company: '未来商事 株式会社', email: 'tanaka@miraishoji.co.jp',   role: '代表取締役 CEO',     reason: '', dup: false },
  { row: 2,  status: 'OK',    name: '山田 花子',    company: 'ネオテック株式会社',  email: 'yamada@neotech.jp',          role: 'CTO',                reason: '', dup: false },
  { row: 3,  status: 'WARN',  name: '鈴木 一郎',    company: '株式会社オリオン',    email: 'suzuki@orion.co.jp',         role: '事業開発部長',       reason: '既存連絡先と重複（メール一致）', dup: true },
  { row: 4,  status: 'OK',    name: '佐藤 美咲',    company: 'スタジオ零',          email: 'misaki@studio-zero.jp',      role: 'デザインディレクター',reason: '', dup: false },
  { row: 5,  status: 'ERROR', name: '',             company: '',                    email: 'invalid_at_example',         role: '営業',               reason: '氏名・会社名のいずれも未入力／メール形式不正', dup: false },
  { row: 6,  status: 'OK',    name: 'James Carter', company: 'Helix Robotics',      email: 'james@helix-robotics.com',   role: 'VP of Sales',        reason: '', dup: false },
  { row: 7,  status: 'WARN',  name: '高橋 直樹',    company: 'コア・ラボ株式会社',  email: 'takahashi@corelabs.jp',      role: '営業企画',           reason: '既存連絡先と重複（メール一致）', dup: true },
  { row: 8,  status: 'OK',    name: '伊藤 さくら',  company: 'グリーンウェイ',      email: 'ito@greenway.co.jp',         role: 'PM',                 reason: '', dup: false },
  { row: 9,  status: 'ERROR', name: '中村 健',      company: '匿名株式会社',        email: '',                            role: '',                   reason: 'メモが 500 字を超過', dup: false },
  { row: 10, status: 'OK',    name: '小林 結衣',    company: 'パスファインダー',    email: 'kobayashi@pathfinder.jp',    role: 'PdM',                reason: '', dup: false },
];

const SUMMARY = { total: 128, ok: 112, warn: 8, error: 8 };

// Reusable colored badge for status
function StatusPill({ status }) {
  const map = {
    OK:    { color: C.cyan,    bg: 'rgba(125,249,255,.10)', icon: 'check',         label: 'OK' },
    WARN:  { color: C.warning, bg: 'rgba(244,184,96,.10)',  icon: 'alert-triangle',label: 'WARN' },
    ERROR: { color: C.magenta, bg: 'rgba(255,110,199,.08)', icon: 'x-octagon',     label: 'ERROR' },
  };
  const s = map[status] || map.OK;
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 4,
      padding: '2px 7px', border: `1px solid ${s.color}`,
      background: s.bg, color: s.color,
      fontFamily: FM, fontSize: 9, letterSpacing: '.1em',
    }}>
      <Icon name={s.icon} size={9} color={s.color} stroke={2} />
      {s.label}
    </span>
  );
}

// Step indicator (4 steps)
function StepIndicator({ current }) {
  const steps = [
    { n: 1, l: 'テンプレート' },
    { n: 2, l: 'ファイル選択' },
    { n: 3, l: 'プレビュー' },
    { n: 4, l: '取込結果' },
  ];
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 4, marginBottom: 18,
      overflowX: 'auto',
    }}>
      {steps.map((st, i) => {
        const done = current > st.n;
        const active = current === st.n;
        return (
          <React.Fragment key={i}>
            <div
              aria-current={active ? 'step' : undefined}
              style={{ display: 'flex', alignItems: 'center', gap: 6, flexShrink: 0 }}
            >
              <div style={{
                width: 22, height: 22,
                border: `1px solid ${active || done ? C.lilac : C.border2}`,
                background: done ? C.lilac : 'transparent',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontFamily: FM, fontSize: 9.5,
                color: done ? C.bg1 : active ? C.lilac : C.fg3,
              }}>
                {done ? <Icon name="check" size={11} color={C.bg1} stroke={2.4} /> : `0${st.n}`}
              </div>
              <span style={{
                fontFamily: FM, fontSize: 9.5,
                color: active ? C.lilac : done ? C.fg2 : C.fg3,
                letterSpacing: '.08em',
                whiteSpace: 'nowrap',
              }}>{st.l}</span>
            </div>
            {i < steps.length - 1 && (
              <span style={{
                flex: 1, minWidth: 12, height: 1,
                background: done ? C.lilac : C.border,
                opacity: done ? 0.5 : 1,
              }} />
            )}
          </React.Fragment>
        );
      })}
    </div>
  );
}

// Reusable section eyebrow
function Eye({ children }) {
  return (
    <div style={{
      fontFamily: FM, fontSize: 9.5, letterSpacing: '.2em',
      color: C.lilac, textTransform: 'uppercase', marginBottom: 10,
    }}>{children}</div>
  );
}

// CSV header column row (used in Step 1)
function ColumnRow({ name, jp, required, hint }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 10,
      padding: '10px 12px',
      borderBottom: `1px dashed ${C.border}`,
    }}>
      <span style={{
        fontFamily: FM, fontSize: 11.5, color: C.cyan,
        minWidth: 70, letterSpacing: '.06em',
      }}>{name}</span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontFamily: FS, fontSize: 12, color: C.fg1 }}>
          {jp}
          {required && <span style={{ color: C.magenta, marginLeft: 6, fontFamily: FM, fontSize: 10 }}>必須*</span>}
        </div>
        {hint && <div style={{ fontFamily: FS, fontSize: 10, color: C.fg3, marginTop: 2 }}>{hint}</div>}
      </div>
    </div>
  );
}

// ─── Step 1 ───────────────────────────────────────────────
function Step1Template({ onNext }) {
  return (
    <div>
      <Eye>// 01 · テンプレート確認</Eye>
      <div style={{
        padding: 14, border: `1px solid ${C.border2}`,
        background: 'linear-gradient(135deg, rgba(125,249,255,.05), transparent)',
        marginBottom: 16,
        borderLeft: `2px solid ${C.cyan}`,
      }}>
        <div style={{ fontFamily: FS, fontSize: 12.5, color: C.fg1, lineHeight: 1.7 }}>
          以下のヘッダ列を含む CSV ファイル（UTF-8）をご用意ください。<br/>
          まずは <strong style={{ color: C.cyan }}>テンプレート</strong> をダウンロードして、お手元のデータを貼り付けるのが確実だなも。
        </div>
      </div>

      <Eye>// 必須ヘッダ列（8 columns）</Eye>
      <div style={{
        border: `1px solid ${C.border}`,
        background: 'rgba(165,154,202,.02)',
        marginBottom: 16,
      }}>
        <ColumnRow name="name"    jp="氏名"    required hint="氏名・会社名のいずれか1つ以上が必須" />
        <ColumnRow name="company" jp="会社名"  required hint="氏名・会社名のいずれか1つ以上が必須" />
        <ColumnRow name="role"    jp="役職" />
        <ColumnRow name="email"   jp="メール" hint="重複検知のキーになる（完全一致）" />
        <ColumnRow name="phone"   jp="電話" />
        <ColumnRow name="address" jp="住所" />
        <ColumnRow name="memo"    jp="補足メモ" hint="500 字以内" />
        <ColumnRow name="tags"    jp="タグ" hint="セミコロン区切り、最大 5 個" />
      </div>

      <Eye>// 制限</Eye>
      <div style={{
        padding: 12, border: `1px solid ${C.border}`,
        background: 'rgba(165,154,202,.02)',
        marginBottom: 18,
        fontFamily: FS, fontSize: 12, color: C.fg2, lineHeight: 1.7,
      }}>
        ・ 1 ファイル <strong style={{ color: C.lilac }}>500 行</strong> まで<br/>
        ・ 1 日累計 <strong style={{ color: C.lilac }}>2,000 行</strong> まで（テナント単位）<br/>
        ・ 文字コード <strong style={{ color: C.lilac }}>UTF-8</strong>（BOM 任意）
      </div>

      <SecondaryBtn full icon="download" style={{ marginBottom: 10 }} onClick={() => window.alert('CSV テンプレートをダウンロード（モック）。\n空のヘッダ行のみ含む cards-template.csv が生成されます。')}>
        テンプレートをダウンロード
      </SecondaryBtn>
      <PrimaryBtn full icon="arrow-right" onClick={onNext}>
        ファイルを選択へ進む
      </PrimaryBtn>
    </div>
  );
}

// ─── Step 2 ───────────────────────────────────────────────
function Step2Pick({ onNext, onBack }) {
  const [picked, setPicked] = useState(false);
  return (
    <div>
      <Eye>// 02 · ファイル選択</Eye>

      {/* Drop zone */}
      <label
        style={{
          display: 'block',
          padding: '32px 20px',
          border: `1.5px dashed ${picked ? C.cyan : C.border2}`,
          background: picked ? 'rgba(125,249,255,.04)' : 'rgba(165,154,202,.02)',
          textAlign: 'center',
          cursor: 'pointer',
          marginBottom: 16,
          transition: 'all 240ms',
        }}
        onClick={(e) => { e.preventDefault(); setPicked(true); }}
      >
        <Icon name={picked ? 'file-check-2' : 'upload-cloud'} size={32} color={picked ? C.cyan : C.lilac} />
        <div style={{ fontFamily: FS, fontSize: 13, color: C.fg1, marginTop: 10, fontWeight: 500 }}>
          {picked ? 'contacts_2026q2.csv' : 'CSV ファイルをここにドロップ'}
        </div>
        <div style={{ fontFamily: FM, fontSize: 10, color: C.fg3, marginTop: 4, letterSpacing: '.06em' }}>
          {picked ? '128 行 · 18.4 KB · UTF-8' : 'またはタップでファイルを選択'}
        </div>
      </label>

      {/* Pre-validation */}
      {picked && (
        <div style={{
          padding: 14, border: `1px solid ${C.border2}`,
          background: 'rgba(165,154,202,.04)',
          marginBottom: 18,
        }}>
          <Eye>// 事前チェック</Eye>
          {[
            { ok: true,  l: 'UTF-8 エンコード'  },
            { ok: true,  l: '必須ヘッダ列 8 列を検出'  },
            { ok: true,  l: '行数 128 / 上限 500'  },
            { ok: true,  l: '本日の累計 372 / 上限 2,000'  },
          ].map((c, i) => (
            <div key={i} style={{
              display: 'flex', alignItems: 'center', gap: 10,
              padding: '7px 0',
              borderTop: i === 0 ? 'none' : `1px solid ${C.border}`,
              fontFamily: FS, fontSize: 12, color: C.fg2,
            }}>
              <Icon name={c.ok ? 'check-circle-2' : 'x-circle'} size={13} color={c.ok ? C.cyan : C.magenta} stroke={2} />
              <span>{c.l}</span>
              <span style={{ marginLeft: 'auto', fontFamily: FM, fontSize: 9.5, color: c.ok ? C.cyan : C.magenta, letterSpacing: '.1em' }}>
                {c.ok ? 'OK' : 'NG'}
              </span>
            </div>
          ))}
        </div>
      )}

      <div style={{ display: 'flex', gap: 8 }}>
        <SecondaryBtn icon="chevron-left" onClick={onBack}>戻る</SecondaryBtn>
        <PrimaryBtn full icon="eye" disabled={!picked} onClick={onNext}>
          プレビューを表示
        </PrimaryBtn>
      </div>
    </div>
  );
}

// ─── Step 3 ───────────────────────────────────────────────
function Step3Preview({ onNext, onBack }) {
  const [policy, setPolicy] = useState('skip'); // overwrite | skip | new
  const [filter, setFilter] = useState('all');  // all | ok | warn | error

  const rows = PREVIEW_ROWS.filter(r => {
    if (filter === 'all') return true;
    if (filter === 'ok')   return r.status === 'OK';
    if (filter === 'warn') return r.status === 'WARN';
    if (filter === 'error')return r.status === 'ERROR';
    return true;
  });

  const policies = [
    { id: 'overwrite', l: '上書き',         sub: '既存を新データで更新', icon: 'replace' },
    { id: 'skip',      l: 'スキップ',       sub: '重複行は取込しない',   icon: 'skip-forward' },
    { id: 'new',       l: '新規として登録', sub: '別レコードとして追加', icon: 'plus-circle' },
  ];

  const onRun = () => {
    if (window.confirm(`OK + 警告行（${SUMMARY.ok + SUMMARY.warn} 件）を取込みます。エラー行 ${SUMMARY.error} 件は除外されます。よろしいですか？`)) {
      onNext();
    }
  };

  return (
    <div>
      <Eye>// 03 · プレビュー & 重複ポリシー</Eye>

      {/* Summary */}
      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)',
        gap: 6, marginBottom: 16,
      }}>
        {[
          { k: 'total', l: '行数',  v: SUMMARY.total, color: C.fg1 },
          { k: 'ok',    l: 'OK',    v: SUMMARY.ok,    color: C.cyan },
          { k: 'warn',  l: 'WARN',  v: SUMMARY.warn,  color: C.warning },
          { k: 'error', l: 'ERROR', v: SUMMARY.error, color: C.magenta },
        ].map(s => (
          <div key={s.k} style={{
            padding: '10px 8px',
            border: `1px solid ${C.border}`,
            background: 'rgba(165,154,202,.02)',
            textAlign: 'center',
          }}>
            <div style={{ fontFamily: FM, fontSize: 9, color: C.fg3, letterSpacing: '.1em' }}>{s.l}</div>
            <div style={{ fontFamily: FF, fontSize: 18, fontWeight: 600, color: s.color, marginTop: 2 }}>{s.v}</div>
          </div>
        ))}
      </div>

      {/* Policy */}
      <Eye>// 重複ポリシー（メール一致時）</Eye>
      <div style={{ marginBottom: 16 }}>
        {policies.map(p => {
          const active = policy === p.id;
          return (
            <div key={p.id}
              onClick={() => setPolicy(p.id)}
              role="radio"
              aria-checked={active}
              tabIndex={0}
              style={{
                display: 'flex', alignItems: 'center', gap: 12,
                padding: '11px 14px',
                border: `1px solid ${active ? C.lilac : C.border}`,
                background: active ? 'rgba(165,154,202,.06)' : 'transparent',
                marginBottom: 6, cursor: 'pointer',
              }}
            >
              <div style={{
                width: 16, height: 16, borderRadius: '50%',
                border: `1px solid ${active ? C.lilac : C.border2}`,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                flexShrink: 0,
              }}>
                {active && <div style={{ width: 8, height: 8, borderRadius: '50%', background: C.lilac }} />}
              </div>
              <Icon name={p.icon} size={14} color={active ? C.lilac : C.fg3} />
              <div style={{ flex: 1 }}>
                <div style={{ fontFamily: FS, fontSize: 12.5, color: active ? C.fg1 : C.fg2, fontWeight: 500 }}>{p.l}</div>
                <div style={{ fontFamily: FS, fontSize: 10.5, color: C.fg3, marginTop: 1 }}>{p.sub}</div>
              </div>
            </div>
          );
        })}
      </div>

      {/* Filter chips */}
      <Eye>// プレビュー（先頭 10 行）</Eye>
      <div style={{ display: 'flex', gap: 6, marginBottom: 10, flexWrap: 'wrap' }}>
        {[
          { id: 'all',   l: 'すべて' },
          { id: 'ok',    l: 'OK のみ' },
          { id: 'warn',  l: '警告' },
          { id: 'error', l: 'エラー' },
        ].map(c => {
          const active = filter === c.id;
          return (
            <button key={c.id}
              onClick={() => setFilter(c.id)}
              style={{
                padding: '5px 11px',
                background: active ? C.lilac : 'transparent',
                color: active ? C.bg1 : C.fg2,
                border: `1px solid ${active ? C.lilac : C.border2}`,
                fontFamily: FM, fontSize: 10, letterSpacing: '.06em',
                cursor: 'pointer',
              }}
            >{c.l}</button>
          );
        })}
      </div>

      {/* Rows */}
      <div style={{ marginBottom: 18 }}>
        {rows.length === 0 && (
          <div style={{ padding: 18, textAlign: 'center', fontFamily: FS, fontSize: 12, color: C.fg3, border: `1px dashed ${C.border}` }}>
            該当する行はありません
          </div>
        )}
        {rows.map(r => (
          <div key={r.row} style={{
            padding: '10px 12px',
            border: `1px solid ${r.status === 'ERROR' ? 'rgba(255,110,199,.32)' : r.status === 'WARN' ? 'rgba(244,184,96,.32)' : C.border}`,
            background: 'rgba(165,154,202,.02)',
            marginBottom: 6,
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
              <span style={{ fontFamily: FM, fontSize: 9.5, color: C.fg3, letterSpacing: '.08em', minWidth: 28 }}>#{r.row}</span>
              <StatusPill status={r.status} />
              {r.dup && (
                <span style={{ fontFamily: FM, fontSize: 9, color: C.warning, padding: '2px 6px', border: `1px solid ${C.warning}`, letterSpacing: '.08em' }}>
                  DUP
                </span>
              )}
            </div>
            <div style={{ fontFamily: FS, fontSize: 12.5, color: C.fg1, fontWeight: 500 }}>
              {r.name || <span style={{ color: C.fg3, fontStyle: 'italic' }}>（氏名なし）</span>}
              {r.company && <span style={{ color: C.fg2, fontWeight: 400 }}> · {r.company}</span>}
            </div>
            <div style={{ fontFamily: FM, fontSize: 10, color: C.fg3, marginTop: 2, letterSpacing: '.04em', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
              {r.email || '— no email —'} · {r.role || '—'}
            </div>
            {r.reason && (
              <div style={{
                marginTop: 6, padding: '6px 8px',
                background: r.status === 'ERROR' ? 'rgba(255,110,199,.06)' : 'rgba(244,184,96,.06)',
                fontFamily: FS, fontSize: 11,
                color: r.status === 'ERROR' ? C.magenta : C.warning,
                lineHeight: 1.5,
              }}>
                {r.reason}
              </div>
            )}
          </div>
        ))}
      </div>

      <div style={{ display: 'flex', gap: 8 }}>
        <SecondaryBtn icon="chevron-left" onClick={onBack}>戻る</SecondaryBtn>
        <PrimaryBtn full icon="upload" onClick={onRun}>取込を実行</PrimaryBtn>
      </div>
    </div>
  );
}

// ─── Step 4 ───────────────────────────────────────────────
function Step4Result({ onRestart }) {
  return (
    <div>
      <Eye>// 04 · 取込結果</Eye>

      {/* Hero icon */}
      <div style={{
        display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10,
        padding: '18px 0 22px',
      }}>
        <div style={{
          width: 64, height: 64,
          border: `1.5px solid ${C.cyan}`,
          background: 'rgba(125,249,255,.06)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          boxShadow: `0 0 24px rgba(125,249,255,.18)`,
        }}>
          <Icon name="check-circle-2" size={30} color={C.cyan} stroke={1.6} />
        </div>
        <div style={{ fontFamily: FF, fontSize: 18, fontWeight: 600, color: C.fg1 }}>取込が完了しました</div>
        <div style={{ fontFamily: FM, fontSize: 10, color: C.fg3, letterSpacing: '.1em' }}>
          // 2026-05-09 14:32 · contacts_2026q2.csv
        </div>
      </div>

      {/* Counts */}
      <div style={{ marginBottom: 18 }}>
        {[
          { l: '新規追加',     v: 105, color: C.cyan,    icon: 'plus-circle' },
          { l: '上書き',       v: 7,   color: C.lilac,   icon: 'replace' },
          { l: 'スキップ（重複）', v: 8, color: C.warning, icon: 'skip-forward' },
          { l: 'エラー',       v: 8,   color: C.magenta, icon: 'x-octagon' },
        ].map((s, i) => (
          <div key={i} style={{
            display: 'flex', alignItems: 'center', gap: 12,
            padding: '12px 14px',
            border: `1px solid ${C.border}`,
            background: 'rgba(165,154,202,.02)',
            marginBottom: 6,
          }}>
            <div style={{
              width: 32, height: 32, border: `1px solid ${s.color}`,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              flexShrink: 0,
            }}>
              <Icon name={s.icon} size={14} color={s.color} stroke={1.8} />
            </div>
            <span style={{ flex: 1, fontFamily: FS, fontSize: 13, color: C.fg1 }}>{s.l}</span>
            <span style={{ fontFamily: FF, fontSize: 18, fontWeight: 600, color: s.color }}>{s.v}</span>
            <span style={{ fontFamily: FM, fontSize: 9.5, color: C.fg3, letterSpacing: '.06em' }}>件</span>
          </div>
        ))}
      </div>

      {/* Audit log notice */}
      <div style={{
        padding: 12, border: `1px solid ${C.border}`,
        borderLeft: `2px solid ${C.lilac}`,
        background: 'rgba(165,154,202,.04)',
        marginBottom: 18,
        fontFamily: FS, fontSize: 11.5, color: C.fg2, lineHeight: 1.6,
      }}>
        <div style={{ fontFamily: FM, fontSize: 9.5, color: C.lilac, letterSpacing: '.16em', marginBottom: 4 }}>// AUDIT LOG</div>
        この取込は監査ログに記録されました（実行者・件数・ファイル名）。`consultant`／`operations` から閲覧できるだなも。
      </div>

      {/* Actions */}
      <SecondaryBtn full icon="file-down" style={{ marginBottom: 8 }}
        onClick={() => window.alert('エラー行のみの CSV をダウンロード（モック）。\nimport_errors_2026-05-09T14-32.csv\n行番号 / 各列 / エラー理由 を含みます。')}
      >
        エラー行のみ CSV をダウンロード
      </SecondaryBtn>
      <PrimaryBtn full icon="credit-card" style={{ marginBottom: 8 }}
        onClick={() => window.SKG_NAV && window.SKG_NAV.go('cards')}
      >
        名刺一覧を見る
      </PrimaryBtn>
      <div
        onClick={onRestart}
        style={{
          textAlign: 'center', padding: '10px 0',
          fontFamily: FM, fontSize: 11, color: C.lilac, letterSpacing: '.08em',
          cursor: 'pointer',
        }}
      >
        ↻ もう一度インポート
      </div>
    </div>
  );
}

// ─── Main wrapper ─────────────────────────────────────────
function CardImportScreen() {
  const [step, setStep] = useState(1);

  return (
    <>
      <AppHeader title="名刺データを一括インポート" subtitle="// CSV BULK IMPORT" back />
      <div style={{ flex: 1, overflow: 'auto', padding: '18px 18px 100px' }}>
        <StepIndicator current={step} />

        {step === 1 && <Step1Template onNext={() => setStep(2)} />}
        {step === 2 && <Step2Pick     onNext={() => setStep(3)} onBack={() => setStep(1)} />}
        {step === 3 && <Step3Preview  onNext={() => setStep(4)} onBack={() => setStep(2)} />}
        {step === 4 && <Step4Result   onRestart={() => setStep(1)} />}
      </div>
      <ConsultFAB />
      <BottomNav active="cards" />
    </>
  );
}

window.SKG_IMPORT = { CardImportScreen };
