// fukui-map.jsx — 福井県 市町別 物件検索マップ
// ▼ リンク先URLはここを編集してください（'#' のままだとリンク無効表示）
const FUKUI_LINKS = {
  'あわら市': { land: 'https://asp.athome.jp/074464/tokushu/20260901151425', house: 'https://asp.athome.jp/074464/tokushu/20260913103006', mansion: 'https://asp.athome.jp/074464/tokushu/20260913211037' },
  '坂井市': { land: 'https://asp.athome.jp/074464/tokushu/20260903151627', house: 'https://asp.athome.jp/074464/tokushu/20260913103241', mansion: 'https://asp.athome.jp/074464/tokushu/20260913204205' },
  '福井市': { land: 'https://asp.athome.jp/074464/tokushu/20260901142944', house: 'https://asp.athome.jp/074464/tokushu/20260913102357', mansion: 'https://asp.athome.jp/074464/tokushu/20260913202455' },
  '永平寺町': { land: 'https://asp.athome.jp/074464/tokushu/20260910172044', house: 'https://asp.athome.jp/074464/tokushu/20260913103352', mansion: 'https://asp.athome.jp/074464/tokushu/20260913203216' },
  '勝山市': { land: 'https://asp.athome.jp/074464/tokushu/20260910172457', house: 'https://asp.athome.jp/074464/tokushu/20260913103508', mansion: 'https://asp.athome.jp/074464/tokushu/20260914083157' },
  '大野市': { land: 'https://asp.athome.jp/074464/tokushu/20260910172549', house: 'https://asp.athome.jp/074464/tokushu/20260913115329', mansion: 'https://asp.athome.jp/074464/tokushu/20260914083242' },
  '鯖江市': { land: 'https://asp.athome.jp/074464/tokushu/20260912110436', house: 'https://asp.athome.jp/074464/tokushu/20260913115920', mansion: 'https://asp.athome.jp/074464/tokushu/20260913204421' },
  '越前町': { land: 'https://asp.athome.jp/074464/tokushu/20260913095656', house: 'https://asp.athome.jp/074464/tokushu/20260914083632', mansion: 'https://asp.athome.jp/074464/tokushu/20260914101822' },
  '越前市': { land: 'https://asp.athome.jp/074464/tokushu/20260912105829', house: 'https://asp.athome.jp/074464/tokushu/20260913200721', mansion: 'https://asp.athome.jp/074464/tokushu/20260914084055' },
  '池田町': { land: 'https://asp.athome.jp/074464/tokushu/20260913095947', house: 'https://asp.athome.jp/074464/tokushu/20260913201437', mansion: 'https://asp.athome.jp/074464/tokushu/20260914101258' },
  '南越前町': { land: 'https://asp.athome.jp/074464/tokushu/20260912110247', house: 'https://asp.athome.jp/074464/tokushu/20260913200856', mansion: 'https://asp.athome.jp/074464/tokushu/20260914083325' },
  '敦賀市': { land: 'https://asp.athome.jp/074464/tokushu/20260913101149', house: 'https://asp.athome.jp/074464/tokushu/20260913201204', mansion: 'https://asp.athome.jp/074464/tokushu/20260913202932' },
  '美浜町': { land: 'https://asp.athome.jp/074464/tokushu/20260913101441', house: 'https://asp.athome.jp/074464/tokushu/20260913201105', mansion: 'https://asp.athome.jp/074464/tokushu/20260914101425' },
  '若狭町': { land: 'https://asp.athome.jp/074464/tokushu/20260913101632', house: 'https://asp.athome.jp/074464/tokushu/20260913201253', mansion: 'https://asp.athome.jp/074464/tokushu/20260914101748' },
  '小浜市': { land: 'https://asp.athome.jp/074464/tokushu/20260912110939', house: 'https://asp.athome.jp/074464/tokushu/20260913120433', mansion: 'https://asp.athome.jp/074464/tokushu/20260914101902' },
  'おおい町': { land: 'https://asp.athome.jp/074464/tokushu/20260913102041', house: 'https://asp.athome.jp/074464/tokushu/20260913202032', mansion: 'https://asp.athome.jp/074464/tokushu/20260914102238' },
  '高浜町': { land: 'https://asp.athome.jp/074464/tokushu/20260913102203', house: 'https://asp.athome.jp/074464/tokushu/20260913201800', mansion: 'https://asp.athome.jp/074464/tokushu/20260914102131' },
};
// 北→南の表示順（スマホ用リスト）
const FUKUI_ORDER = Object.keys(FUKUI_LINKS);
// ラベル位置の微調整 [x, y]（地図座標 px）
const FUKUI_LABEL_NUDGE = {
  'あわら市': [0, -6], '坂井市': [-10, 6], '福井市': [-30, -10], '永平寺町': [10, 8],
  '越前町': [-6, 0], '鯖江市': [4, 0], '越前市': [-10, 10], '池田町': [4, 0], '南越前町': [10, 20],
  '美浜町': [0, 10], '若狭町': [0, 14], 'おおい町': [0, 12],
};

// スマホ時のみの追加調整 [x, y]
const FUKUI_LABEL_NUDGE_SP = {
  '永平寺町': [5, 40], '福井市': [-30, 0], '越前町': [-45, 0], '若狭町': [0, -22],
};

const fukuiMapStyles = {
  pill: {
    position: 'absolute', transform: 'translate(-50%, -50%)', whiteSpace: 'nowrap',
    background: '#fff', border: '1px solid var(--ink)', borderRadius: 999,
    fontFamily: 'var(--sans-jp)', fontWeight: 500, color: 'var(--ink)', cursor: 'pointer',
    display: 'flex', alignItems: 'center', gap: 6, lineHeight: 1.2,
    boxShadow: '0 2px 6px rgba(26,26,26,0.12)', transition: 'background .2s, color .2s',
  },
};

const FukuiArrow = ({ size = 22 }) => (
  <span style={{ width: size, height: size, borderRadius: '50%', background: 'var(--pink-500)', color: '#fff', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
    <svg width={size * 0.5} height={size * 0.5} viewBox="0 0 12 12" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M2 6h8M6.5 2.5L10 6l-3.5 3.5" /></svg>
  </span>
);

const FukuiPopup = ({ name, onClose, style }) => {
  const links = FUKUI_LINKS[name] || {};
  const rows = [['土地', links.land], ['戸建て', links.house], ['マンション', links.mansion]];
  return (
    <div role="dialog" aria-label={name} style={{
      background: '#fff', border: '2px solid var(--pink-500)', borderRadius: 18, padding: '22px 26px 18px',
      width: 240, boxShadow: '0 12px 32px rgba(26,26,26,0.16)', position: 'relative', ...style,
    }}>
      <button onClick={onClose} aria-label="閉じる" style={{
        position: 'absolute', top: -14, right: -14, width: 32, height: 32, borderRadius: '50%', border: 'none',
        background: 'var(--pink-500)', color: '#fff', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <svg width="14" height="14" viewBox="0 0 14 14" stroke="currentColor" strokeWidth="2"><path d="M2 2l10 10M12 2L2 12" /></svg>
      </button>
      <div style={{ fontFamily: 'var(--serif-jp)', fontSize: 20, fontWeight: 600, textAlign: 'center', paddingBottom: 12, borderBottom: '1px solid var(--line-strong)', marginBottom: 8 }}>{name}</div>
      <div style={{ display: 'grid' }}>
        {rows.map(([label, href]) => {
          const off = !href || href === '#';
          return (
            <a key={label} href={off ? undefined : href} target="_blank" rel="noopener" aria-disabled={off} style={{
              display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, padding: '10px 2px',
              fontFamily: 'var(--sans-jp)', fontSize: 16, color: 'var(--ink)', textDecoration: 'none',
              letterSpacing: '0.12em', opacity: off ? 0.4 : 1, cursor: off ? 'default' : 'pointer',
            }}>
              <span>{label}</span><FukuiArrow />
            </a>
          );
        })}
      </div>
    </div>
  );
};

const FukuiMap = () => {
  const bp = useBreakpoint();
  const isMobile = bp === 'mobile';
  const [geo, setGeo] = React.useState(null);
  const [sel, setSel] = React.useState(null);
  const [hover, setHover] = React.useState(null);

  React.useEffect(() => {
    fetch('assets/fukui-municipalities.json').then(r => r.json()).then(topo => {
      const key = Object.keys(topo.objects)[0];
      const fc = topojson.feature(topo, topo.objects[key]);
      const W = 1000;
      const proj = d3.geoMercator().fitWidth(W - 40, fc);
      const path = d3.geoPath(proj);
      const [[x0, y0], [, y1]] = path.bounds(fc);
      proj.translate([proj.translate()[0] + 20 - x0, proj.translate()[1] + 20 - y0]);
      const H = Math.ceil(y1 - y0 + 40);
      const items = fc.features.map(f => {
        const name = f.properties.N03_004;
        const c = path.centroid(f);
        const n = FUKUI_LABEL_NUDGE[name] || [0, 0];
        return { name, d: path(f), cx: c[0] + n[0], cy: c[1] + n[1] };
      });
      setGeo({ W, H, items });
    }).catch(() => {});
  }, []);

  React.useEffect(() => {
    if (!sel) return;
    const onKey = e => { if (e.key === 'Escape') setSel(null); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [sel]);

  const posOf = it => {
    const m = isMobile && FUKUI_LABEL_NUDGE_SP[it.name] || [0, 0];
    return [it.cx + m[0], it.cy + m[1]];
  };
  const selItem = geo && sel ? geo.items.find(i => i.name === sel) : null;
  const pillFont = pick(bp, 15, 12.5, 9.5);

  return (
    <div style={{ maxWidth: 1000, margin: '0 auto' }}>
      <p style={{ textAlign: 'center', fontFamily: 'var(--sans-jp)', fontSize: pick(bp, 15, 14, 13), color: 'var(--ink-soft)', margin: '0 0 28px' }}>
        物件を探したい市町の名称をクリックしてください。
      </p>
      <div style={{ position: 'relative', width: '100%', aspectRatio: geo ? `${geo.W} / ${geo.H}` : '1 / 1' }}>
        {geo && (
          <svg viewBox={`0 0 ${geo.W} ${geo.H}`} style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', display: 'block' }}>
            {geo.items.map(it => (
              <path key={it.name} d={it.d}
                fill={sel === it.name ? 'var(--pink-500)' : hover === it.name ? 'var(--pink-400)' : 'var(--pink-300)'}
                stroke="#fff" strokeWidth={pick(bp, 3, 3, 4)} strokeLinejoin="round"
                style={{ cursor: 'pointer', transition: 'fill .2s' }}
                onMouseEnter={() => setHover(it.name)} onMouseLeave={() => setHover(null)}
                onClick={() => setSel(it.name)}
              />
            ))}
          </svg>
        )}
        {geo && geo.items.map(it => (
          <button key={it.name} onClick={() => setSel(it.name)}
            onMouseEnter={() => setHover(it.name)} onMouseLeave={() => setHover(null)}
            style={{
              ...fukuiMapStyles.pill, left: `${posOf(it)[0] / geo.W * 100}%`, top: `${posOf(it)[1] / geo.H * 100}%`,
              fontSize: pillFont, padding: pick(bp, '7px 16px', '5px 11px', '3px 7px'), gap: isMobile ? 3 : 6,
              background: sel === it.name || hover === it.name ? 'var(--ink)' : '#fff',
              color: sel === it.name || hover === it.name ? '#fff' : 'var(--ink)',
            }}>
            {it.name}<span aria-hidden="true">→</span>
          </button>
        ))}
        {selItem && !isMobile && (
          <div style={{
            position: 'absolute', zIndex: 5,
            top: `clamp(0px, calc(${selItem.cy / geo.H * 100}% - 110px), calc(100% - 240px))`,
            ...(selItem.cx / geo.W < 0.5
              ? { left: `calc(${selItem.cx / geo.W * 100}% + 90px)` }
              : { right: `calc(${(1 - selItem.cx / geo.W) * 100}% + 90px)` }),
          }}>
            <FukuiPopup name={sel} onClose={() => setSel(null)} />
          </div>
        )}
      </div>

      {sel && isMobile && (
        <div onClick={() => setSel(null)} style={{ position: 'fixed', inset: 0, zIndex: 200, background: 'rgba(26,26,26,0.45)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <div onClick={e => e.stopPropagation()}><FukuiPopup name={sel} onClose={() => setSel(null)} /></div>
        </div>
      )}

    </div>
  );
};

Object.assign(window, { FukuiMap, FUKUI_LINKS });
