// ╔══════════════════════════════════════════════════════════╗
// ║            六命解析 — LIFE CODE ENGINE v2               ║
// ╚══════════════════════════════════════════════════════════╝

// ═══ SHICHUSUIMEI (四柱推命) ═══
const STEMS  = ['甲','乙','丙','丁','戊','己','庚','辛','壬','癸'];
const STEM_EL = ['木','木','火','火','土','土','金','金','水','水'];
const BRANCHES = ['子','丑','寅','卯','辰','巳','午','未','申','酉','戌','亥'];
const BRANCH_ANIMALS = ['鼠','牛','虎','兔','龍','蛇','馬','羊','猿','鶏','犬','猪'];
const BRANCH_EL = ['水','土','木','木','土','火','火','土','金','金','土','水'];
const ELEMENTS = ['木','火','土','金','水'];
const ELEMENT_DATA = {
  '木': { title:'木気', nature:'成長・発展・柔軟性', season:'春', dir:'東',  desc:'生命の芽吹きを司る。常に上へ向かう成長のエネルギー。', color:'#5a9e8a' },
  '火': { title:'火気', nature:'情熱・変革・輝き',   season:'夏', dir:'南',  desc:'炎のように周囲を照らし、変化をもたらす強烈なエネルギー。', color:'#c06060' },
  '土': { title:'土気', nature:'安定・包容・中庸',   season:'土用',dir:'中央',desc:'万物を育む大地の力。バランスを保ち全てを包み込む。', color:'#c8a84b' },
  '金': { title:'金気', nature:'収穫・精錬・完璧',   season:'秋', dir:'西',  desc:'純粋さを追求し、不要なものを削ぎ落とす刃のエネルギー。', color:'#9090b0' },
  '水': { title:'水気', nature:'智慧・流動・深淵',   season:'冬', dir:'北',  desc:'深い知性と適応力。あらゆる形に変化する無限の可能性。', color:'#5080a0' },
};

function getYearPillar(year) {
  const si = ((year - 4) % 10 + 10) % 10;
  const bi = ((year - 4) % 12 + 12) % 12;
  return { stem: STEMS[si], branch: BRANCHES[bi], el: STEM_EL[si], animal: BRANCH_ANIMALS[bi] };
}
function getMonthPillar(year, month) {
  const yearStemIdx = ((year - 4) % 10 + 10) % 10;
  const monthBase = Math.floor(yearStemIdx / 2) * 2;
  const si = (monthBase + (month - 1)) % 10;
  const bi = (month + 1) % 12;
  return { stem: STEMS[si], branch: BRANCHES[bi], el: STEM_EL[si] };
}
function getDayPillar(year, month, day) {
  const a = Math.floor((14 - month) / 12);
  const y = year - a, m2 = month + 12 * a - 2;
  const jd = day + Math.floor((153 * m2 + 2) / 5) + 365 * y + Math.floor(y/4) - Math.floor(y/100) + Math.floor(y/400) - 32045;
  const si = ((jd + 9) % 10 + 10) % 10;
  const bi = ((jd + 1) % 12 + 12) % 12;
  return { stem: STEMS[si], branch: BRANCHES[bi], el: STEM_EL[si] };
}
function getHourPillar(hour) {
  // 子時=23-1, 丑時=1-3, ...
  const branchIdx = Math.floor(((hour + 1) % 24) / 2) % 12;
  return { branch: BRANCHES[branchIdx], el: BRANCH_EL[branchIdx], animal: BRANCH_ANIMALS[branchIdx] };
}
function getDominantEl(year, month, day, hour) {
  const yp = getYearPillar(year), mp = getMonthPillar(year,month), dp = getDayPillar(year,month,day);
  const hp = hour !== null ? getHourPillar(hour) : null;
  const counts = {};
  [yp.el, mp.el, dp.el, hp?.el].filter(Boolean).forEach(e => { counts[e] = (counts[e]||0)+1; });
  return Object.entries(counts).sort((a,b)=>b[1]-a[1])[0][0];
}
function formatHourInputValue(value) {
  if (!value) return '';
  const match = String(value).match(/^(\d{1,2})/);
  if (!match) return '';
  const hour = parseInt(match[1], 10);
  if (Number.isNaN(hour)) return '';
  return String(hour);
}

function formatBirthTimeForStorage(hourValue) {
  const hour = parseInt(String(hourValue ?? '').trim(), 10);
  if (Number.isNaN(hour) || hour < 0 || hour > 23) {
    return null;
  }
  return `${String(hour).padStart(2, '0')}:00:00`;
}

function normalizeOptionalDecimalString(value, min, max) {
  if (value === null || typeof value === 'undefined') {
    return null;
  }
  const trimmed = String(value).trim();
  if (trimmed === '') {
    return null;
  }
  const num = parseFloat(trimmed);
  if (Number.isNaN(num) || num < min || num > max) {
    return null;
  }
  return trimmed;
}

function formatBirthLatLngValue(lat, lng) {
  const latStr = lat != null && String(lat).trim() !== '' ? String(lat).trim() : '';
  const lngStr = lng != null && String(lng).trim() !== '' ? String(lng).trim() : '';
  if (latStr && lngStr) {
    return `${latStr}, ${lngStr}`;
  }
  return latStr || lngStr || '';
}

function parseBirthLatLngValue(rawValue) {
  const raw = String(rawValue ?? '').trim();
  if (raw === '') {
    return { birthLatitude: null, birthLongitude: null };
  }
  const matches = raw.replace(/[，]/g, ',').match(/-?\d+(?:\.\d+)?/g);
  if (!matches || matches.length < 2) {
    return { birthLatitude: null, birthLongitude: null };
  }
  return {
    birthLatitude: normalizeOptionalDecimalString(matches[0], -90, 90),
    birthLongitude: normalizeOptionalDecimalString(matches[1], -180, 180),
  };
}

function adjustDateTimeByLongitude(birthDateValue, timeValue, longitude, referenceLongitude = 135) {
  const dateStr = String(birthDateValue ?? '').trim();
  const timeStr = String(timeValue ?? '').trim();
  const lon = parseFloat(String(longitude ?? '').trim());
  if (!dateStr || !timeStr || Number.isNaN(lon)) {
    return null;
  }

  const dateMatch = dateStr.match(/^(\d{4})-(\d{2})-(\d{2})$/);
  const timeMatch = timeStr.match(/^(\d{1,2})(?::(\d{2})(?::(\d{2}))?)?$/);
  if (!dateMatch || !timeMatch) {
    return null;
  }

  const year = parseInt(dateMatch[1], 10);
  const month = parseInt(dateMatch[2], 10);
  const day = parseInt(dateMatch[3], 10);
  const hour = parseInt(timeMatch[1], 10);
  const minute = timeMatch[2] ? parseInt(timeMatch[2], 10) : 0;
  const second = timeMatch[3] ? parseInt(timeMatch[3], 10) : 0;
  if ([year, month, day, hour, minute, second].some(Number.isNaN)) {
    return null;
  }

  const offsetMinutes = Math.round((lon - referenceLongitude) * 4);
  const baseUtc = Date.UTC(year, month - 1, day, hour, minute, second);
  const adjusted = new Date(baseUtc + offsetMinutes * 60 * 1000);
  if (Number.isNaN(adjusted.getTime())) {
    return null;
  }

  const adjustedDate = `${adjusted.getUTCFullYear()}-${String(adjusted.getUTCMonth() + 1).padStart(2, '0')}-${String(adjusted.getUTCDate()).padStart(2, '0')}`;
  const adjustedTime = `${String(adjusted.getUTCHours()).padStart(2, '0')}:${String(adjusted.getUTCMinutes()).padStart(2, '0')}:${String(adjusted.getUTCSeconds()).padStart(2, '0')}`;
  return { birthDate: adjustedDate, birthTime: adjustedTime, offsetMinutes };
}

// ═══ SUUHI (数秘術) ═══
function calcLifePath(year, month, day) {
  const digits = `${year}${String(month).padStart(2,'0')}${String(day).padStart(2,'0')}`;
  let s = digits.split('').reduce((a,b)=>a+parseInt(b),0);
  while (s > 9 && s !== 11 && s !== 22 && s !== 33) {
    s = s.toString().split('').reduce((a,b)=>a+parseInt(b),0);
  }
  return s;
}
const LIFEPATH_DATA = {
  1:  { title:'先駆者', keywords:['独立','創造','主導'] },
  2:  { title:'調和者', keywords:['協力','直感','調和'] },
  3:  { title:'表現者', keywords:['創造','表現','喜び'] },
  4:  { title:'建設者', keywords:['安定','規律','実直'] },
  5:  { title:'探求者', keywords:['自由','変化','冒険'] },
  6:  { title:'保護者', keywords:['愛情','責任','奉仕'] },
  7:  { title:'探偵者', keywords:['探求','直観','神秘'] },
  8:  { title:'支配者', keywords:['成功','野心','豊かさ'] },
  9:  { title:'完成者', keywords:['完成','奉仕','智慧'] },
  11: { title:'照明者', keywords:['啓示','直観','霊性'] },
  22: { title:'建築者', keywords:['実現','偉業','建設'] },
  33: { title:'教師',   keywords:['愛','癒し','教育']   },
};

// ═══ KYUSEI (九星気学) ═══
const KYUSEI_NAMES  = ['一白水星','二黒土星','三碧木星','四緑木星','五黄土星','六白金星','七赤金星','八白土星','九紫火星'];
const KYUSEI_DIRS   = ['北','南西','東','東南','中央','北西','西','北東','南'];
const KYUSEI_COLORS = ['#4a7fa0','#604030','#4a7a60','#5a8060','#b8963c','#8090a0','#c04850','#8090a0','#a040a0'];
function calcKyusei(year, month) {
  const base = ((year - 1984) % 9 + 9) % 9;
  const adj  = [0,8,7,6,5,4,3,2,1,0,8,7,6][month] || 0;
  return ((base + adj) % 9) + 1;
}

// ═══ ZODIAC (12星座) ═══
function getZodiac(month, day) {
  const tbl = [
    [1,20,'水瓶座','♒'],[2,19,'魚座','♓'],[3,21,'牡羊座','♈'],
    [4,20,'牡牛座','♉'],[5,21,'双子座','♊'],[6,21,'蟹座','♋'],
    [7,23,'獅子座','♌'],[8,23,'乙女座','♍'],[9,23,'天秤座','♎'],
    [10,23,'蠍座','♏'],[11,22,'射手座','♐'],[12,22,'山羊座','♑'],
  ];
  for (let i=0;i<tbl.length;i++) {
    const [m,d,name,sym] = tbl[i];
    if (month===m && day<d) return {name,symbol:sym};
    if (month===m && day>=d) { const n=tbl[(i+1)%12]; return {name:n[2],symbol:n[3]}; }
  }
  return {name:'山羊座',symbol:'♑'};
}

// ═══ BIORHYTHM ═══
function calcBio(by,bm,bd,ty,tm,td) {
  const days = Math.floor((new Date(ty,tm-1,td)-new Date(by,bm-1,bd))/(86400000));
  return {
    physical:    Math.sin(2*Math.PI*days/23),
    emotional:   Math.sin(2*Math.PI*days/28),
    intellectual:Math.sin(2*Math.PI*days/33),
    days,
  };
}

// ═══ MAYA ═══
const MAYA_KINS  = ['イミシュ','イク','アクバル','カン','チクチャン','キミ','マニク','ラマット','ムルク','オク','チュエン','エブ','ベン','イシュ','メン','キブ','カバン','エツナブ','カワク','アハウ'];
const MAYA_TONES = ['磁気','月','電気','自己存在','倍音','韻律','共鳴','銀河','太陽','惑星','スペクトル','水晶','宇宙'];
function calcMaya(y,m,d) {
  const diff = Math.floor((new Date(y,m-1,d)-new Date(2013,0,1))/86400000);
  const kin  = ((diff%20)+20)%20;
  const tone = ((diff%13)+13)%13;
  return { kin:MAYA_KINS[kin], tone:MAYA_TONES[tone], kinNum:kin+1, toneNum:tone+1 };
}

function getTransitionBucketMeta(evt) {
  const bucket = evt?.transition_bucket || '';
  switch (bucket) {
    case 'event_type_event_text_transition':
      return { label: '転機候補', tone: 'high', note: '動きが大きいイベントとして優先表示' };
    case 'event_type_event_short_description':
      return { label: '要確認', tone: 'medium', note: '説明が短いため、参考として表示' };
    case 'event_type_event_other':
      return { label: '参考', tone: 'low', note: '通常のイベントとして控えめに表示' };
    case 'event_type_event_date_only':
      return { label: '除外', tone: 'exclude', note: '日付見出しのみのため表示対象外' };
    default:
      return null;
  }
}

// ═══════════════════════════════════════════════════════
//  OS SYSTEM — Drive・Care・Vision・Logic・Quest・Balance
// ═══════════════════════════════════════════════════════

// 各占術から 6つのOS点（0-20）を返すマッピング
const ELEMENT_OS = {
  '木': { Drive:8,  Care:12, Vision:18, Logic:8,  Quest:16, Balance:14 },
  '火': { Drive:18, Care:12, Vision:14, Logic:8,  Quest:14, Balance:10 },
  '土': { Drive:8,  Care:18, Vision:12, Logic:14, Quest:6,  Balance:18 },
  '金': { Drive:12, Care:10, Vision:8,  Logic:20, Quest:12, Balance:14 },
  '水': { Drive:10, Care:14, Vision:16, Logic:16, Quest:12, Balance:8  },
};

const LIFEPATH_OS = {
  1:{Drive:20,Care:6, Vision:14,Logic:12,Quest:16,Balance:8 },
  2:{Drive:6, Care:20,Vision:10,Logic:12,Quest:6, Balance:18},
  3:{Drive:14,Care:12,Vision:20,Logic:8, Quest:14,Balance:12},
  4:{Drive:10,Care:14,Vision:8, Logic:20,Quest:8, Balance:16},
  5:{Drive:16,Care:8, Vision:14,Logic:10,Quest:20,Balance:10},
  6:{Drive:8, Care:18,Vision:14,Logic:12,Quest:8, Balance:18},
  7:{Drive:6, Care:10,Vision:18,Logic:20,Quest:12,Balance:12},
  8:{Drive:18,Care:10,Vision:10,Logic:18,Quest:12,Balance:10},
  9:{Drive:12,Care:18,Vision:16,Logic:10,Quest:14,Balance:14},
  11:{Drive:8,Care:12,Vision:20,Logic:14,Quest:12,Balance:16},
  22:{Drive:16,Care:12,Vision:14,Logic:18,Quest:10,Balance:14},
  33:{Drive:8,Care:20,Vision:16,Logic:10,Quest:8, Balance:18},
};

const KYUSEI_OS = {
  1:{Drive:8, Care:12,Vision:16,Logic:18,Quest:10,Balance:12},
  2:{Drive:8, Care:18,Vision:10,Logic:12,Quest:6, Balance:20},
  3:{Drive:16,Care:10,Vision:18,Logic:8, Quest:18,Balance:12},
  4:{Drive:14,Care:12,Vision:20,Logic:10,Quest:16,Balance:14},
  5:{Drive:20,Care:12,Vision:12,Logic:16,Quest:12,Balance:14},
  6:{Drive:12,Care:10,Vision:10,Logic:20,Quest:12,Balance:18},
  7:{Drive:10,Care:12,Vision:18,Logic:14,Quest:12,Balance:14},
  8:{Drive:10,Care:14,Vision:8, Logic:18,Quest:10,Balance:20},
  9:{Drive:18,Care:12,Vision:16,Logic:10,Quest:14,Balance:12},
};

const ZODIAC_OS = {
  '牡羊座':{Drive:20,Care:8, Vision:14,Logic:8, Quest:16,Balance:10},
  '牡牛座':{Drive:8, Care:16,Vision:10,Logic:14,Quest:8, Balance:20},
  '双子座':{Drive:14,Care:10,Vision:18,Logic:12,Quest:18,Balance:12},
  '蟹座':  {Drive:6, Care:20,Vision:12,Logic:10,Quest:6, Balance:18},
  '獅子座':{Drive:18,Care:12,Vision:18,Logic:8, Quest:14,Balance:10},
  '乙女座':{Drive:8, Care:14,Vision:10,Logic:20,Quest:10,Balance:16},
  '天秤座':{Drive:12,Care:14,Vision:14,Logic:12,Quest:12,Balance:20},
  '蠍座':  {Drive:12,Care:16,Vision:16,Logic:18,Quest:14,Balance:8 },
  '射手座':{Drive:16,Care:10,Vision:14,Logic:10,Quest:20,Balance:12},
  '山羊座':{Drive:14,Care:12,Vision:8, Logic:18,Quest:10,Balance:18},
  '水瓶座':{Drive:12,Care:8, Vision:20,Logic:14,Quest:18,Balance:14},
  '魚座':  {Drive:6, Care:18,Vision:18,Logic:8, Quest:12,Balance:16},
};

function getMayaOS(kinNum) {
  const g = Math.ceil(kinNum / 5);
  return [
    {Drive:16,Care:14,Vision:12,Logic:12,Quest:14,Balance:14},
    {Drive:14,Care:14,Vision:16,Logic:12,Quest:14,Balance:12},
    {Drive:12,Care:14,Vision:14,Logic:16,Quest:16,Balance:12},
    {Drive:12,Care:16,Vision:14,Logic:14,Quest:12,Balance:16},
  ][g - 1] || {Drive:13,Care:13,Vision:13,Logic:13,Quest:13,Balance:13};
}

const OS_TYPES = ['Drive','Care','Vision','Logic','Quest','Balance'];
const OS_META = {
  Drive:   { label:'🔥 点火者', jpName:'点火者', detailType:'先行突破型', emoji:'🔥', color:'#e07040', tagline:'行動・推進・決断' },
  Care:    { label:'🌙 包容者', jpName:'包容者', detailType:'信頼構築型', emoji:'🌙', color:'#5080a0', tagline:'共感・支援・調和' },
  Vision:  { label:'🎨 表現者', jpName:'表現者', detailType:'世界観創造型', emoji:'🎨', color:'#a050a0', tagline:'創造・直感・洞察' },
  Logic:   { label:'💎 洞察者', jpName:'洞察者', detailType:'本質解析型', emoji:'💎', color:'#6090c0', tagline:'分析・計画・精緻' },
  Quest:   { label:'🪽 解放者', jpName:'解放者', detailType:'変化適応型', emoji:'🪽', color:'#508060', tagline:'探求・冒険・自由' },
  Balance: { label:'🌿 調律者', jpName:'調律者', detailType:'調和設計型', emoji:'🌿', color:'#c8a84b', tagline:'統合・調和・柔軟' },
};

// OSタイプ別の職業適性と成功確率（バックテストデータに基づく）
const OS_CAREER_MAP = {
  Drive: {
    primary: { career: '起業家・経営者', successRate: 100 },
    subModifiers: {
      Care: '思いやりのある',
      Vision: 'クリエイティブな',
      Logic: '戦略的な',
      Quest: '変革的な',
      Balance: 'バランス感覚のある',
    }
  },
  Vision: {
    primary: { career: 'ミュージシャン・アーティスト', successRate: 87.5 },
    subModifiers: {
      Drive: 'ビジネスセンスのある',
      Care: '人の心に寄り添う',
      Logic: '意図的な',
      Quest: '多様な表現の',
      Balance: 'バランス感覚のある',
    }
  },
  Quest: {
    primary: { career: '起業家・営業・フリーランス', successRate: 100 },
    subModifiers: {
      Drive: '推進力のある',
      Care: '信頼を築く',
      Vision: 'クリエイティブな',
      Logic: '分析眼のある',
      Balance: 'バランス感覚のある',
    }
  },
  Balance: {
    primary: { career: 'マネージャー・コーディネーター', successRate: 69.5 },
    subModifiers: {
      Drive: '決断力のある',
      Care: '人を育てる',
      Vision: 'クリエイティブな',
      Logic: '分析的な',
      Quest: '適応力のある',
    }
  },
  Care: {
    primary: { career: 'カウンセラー・教育者・福祉職', successRate: 69.5 },
    subModifiers: {
      Drive: 'リーダーシップのある',
      Vision: 'クリエイティブな',
      Logic: '分析的な',
      Quest: '開放的な',
      Balance: 'バランス感覚のある',
    }
  },
  Logic: {
    primary: { career: '研究者・分析家・戦略家', successRate: 69.5 },
    subModifiers: {
      Drive: 'ビジネスセンスのある',
      Care: '共感力のある',
      Vision: 'クリエイティブな',
      Quest: '探究心の強い',
      Balance: 'バランス感覚のある',
    }
  },
};

// OSタイプの組み合わせから職業と成功確率を取得
const getOSCareerInfo = (mainOS, subOS) => {
  const mainCareer = OS_CAREER_MAP[mainOS];
  if (!mainCareer) return null;

  const modifier = mainCareer.subModifiers[subOS] || '';
  const careerLabel = modifier ? `${modifier}${mainCareer.primary.career}` : mainCareer.primary.career;

  return {
    career: careerLabel,
    successRate: mainCareer.primary.successRate,
    mainCareerType: mainCareer.primary.career,
  };
};

// 層1：OSスコア計算（仕様の重み付け）
function calcOSScores(lifePath, el, kyusei, zodiac, maya) {
  const s = Object.fromEntries(OS_TYPES.map(k=>[k,0]));
  const add = (map, w) => map && OS_TYPES.forEach(k => { s[k] += (map[k]||0) * w; });
  add(ELEMENT_OS[el],         0.35);
  add(LIFEPATH_OS[lifePath],  0.25);
  add(KYUSEI_OS[kyusei],      0.15);
  add(ZODIAC_OS[zodiac.name], 0.10);
  add(getMayaOS(maya.kinNum), 0.15);
  const sorted = Object.entries(s).sort((a,b)=>b[1]-a[1]);
  return { scores: s, mainOS: sorted[0][0], subOS: sorted[1][0] };
}

// ═══════════════════════════════════════════════════════
//  6 TYPE SYSTEM — 点火者・包容者・表現者・洞察者・解放者・調律者（互換性用、将来削除予定）
// ═══════════════════════════════════════════════════════
const SIX_TYPES = {
  '点火者': {
    label:'🚀 先行突破型',
    color:'#e07040',
    tagline:'誰よりも早く、誰よりも遠くへ',
    desc:'物事を一から動かす強烈な推進力を持ちます。停滞を嫌い、常に新しいフロンティアへ向かう。リスクを恐れず、失敗から学ぶ速度が異常に速い。',
    personality:'強い意志と独立心の持ち主。周囲のペースに合わせることが苦手だが、その突破力は他の追随を許さない。感情より理性を優先し、目標達成のためには孤独も厭わない。自分の信念に忠実で、曲げることを嫌う。',
    love:'恋愛においても積極的で、好きになったら一直線。しかし自立心が強く、束縛を嫌うため、対等なパートナーシップが理想。相手の自由も尊重できる人と深く結ばれる。',
    work:'起業家・経営者・プロジェクトリーダーに適性。新規事業の立ち上げや、前例のない挑戦に真価を発揮。金運は行動に比例して高まる。リスクを取った分だけ報われる星の下に生まれている。',
    advice:'「完璧を待つより、今すぐ動く」があなたのテーゼ。ただし、仲間を置き去りにしないよう意識的に振り返る習慣を。',
    compat: ['調律者', '解放者'],
  },
  '包容者': {
    label:'💝 信頼構築型',
    color:'#c06080',
    tagline:'すべてを受け入れ、すべてを育む',
    desc:'深い愛情と受容力で、周囲に安心の場を作ります。人の痛みを自分のこととして感じ取る共感力の持ち主。',
    personality:'繊細で感受性が豊か。表には出さないが、内側では常に深く考えている。人間関係を大切にし、誰かの役に立つことで自分の存在意義を感じる。ただし自己犠牲が過ぎると燃え尽きやすい。',
    love:'深く、真剣に愛する。一度結ばれると長く続く傾向。相手の感情を敏感に察知するため、言葉がなくても通じ合える関係を築く。嫉妬心は強いが、それは愛の深さの裏返し。',
    work:'カウンセラー・医療・教育・福祉の分野で才能を発揮。人を育てる仕事に天職を見出す。金運は「与えること」から循環する。惜しまず与える姿勢が、やがて豊かさとして返ってくる。',
    advice:'「No」と言う練習をしてください。あなたの優しさを守るために、境界線を引くことは愛の行為です。',
    compat: ['洞察者', '表現者'],
  },
  '表現者': {
    label:'🎨 世界観創造型',
    color:'#8060c0',
    tagline:'言葉と色彩で、世界を塗り替える',
    desc:'豊かな創造性と独自の世界観を持ち、表現することで魂が輝きます。芸術・言語・音楽などあらゆる媒体を通じて、見えない何かを可視化する力。',
    personality:'個性的で独創的。マイペースで、流行より自分のスタイルを貫く。気分の波が激しいことがあるが、その振れ幅が創造力の源泉。孤独な時間が必要で、それが才能の充電になる。',
    love:'恋愛は情熱的かつ詩的。理想が高く、ありきたりな関係には満足しない。精神的な結びつきを最重視し、魂の共鳴を感じる人との縁が深まる。',
    work:'アーティスト・作家・デザイナー・ミュージシャンなど創造的職業に天賦の才。また、マーケティングやブランディングでも独自センスが光る。金運は「好きなことをする」ことで引き寄せられる。',
    advice:'完璧主義を手放すと、作品がさらに自由になります。未完成のままでも、世界に出す勇気を持ってください。',
    compat: ['包容者', '調律者'],
  },
  '洞察者': {
    label:'🧠 本質解析型',
    color:'#4070a0',
    tagline:'見えないものを見る、静かな哲人',
    desc:'深い分析力と直観を持ち、物事の本質を瞬時に見抜きます。表面的な情報に惑わされず、構造と真実を追求する。',
    personality:'内向的で思慮深い。会話より観察を好み、言葉を大切に使う。少数精鋭の深い関係を好み、広く浅い付き合いには消耗する。知的探求が生きがいで、学ぶことをやめない。',
    love:'恋愛は慎重で、相手を深く理解してから動く。表面的な魅力より、知性と誠実さに惹かれる。一度心を開いた相手には深い信頼を寄せるが、裏切りには敏感。',
    work:'研究者・分析家・戦略家・医師・哲学者など。データと洞察を組み合わせる仕事で真価を発揮。金運は「専門性を極める」ことで安定する。浅く広くより、深く狭く。',
    advice:'知識を行動に変える練習を。分析が終わったら、まず一歩だけ動いてみてください。思考と行動のバランスが運を開きます。',
    compat: ['包容者', '点火者'],
  },
  '解放者': {
    label:'🌍 変化適応型',
    color:'#50a070',
    tagline:'枠を超え、風のように自由に',
    desc:'変化と自由を愛し、あらゆる環境に適応する柔軟性を持ちます。固定観念を打ち破り、新しいパラダイムをもたらす変革者。',
    personality:'好奇心旺盛で飽きやすい面もあるが、その多様な経験が独自の視点を生む。ルールより自由、安定より変化。旅・異文化・新しい体験が魂の栄養となる。人脈が広く、縁の引力が強い。',
    love:'恋愛は自由で軽やか。重い関係より、互いに成長し合えるパートナーシップを好む。単調さを嫌うため、常に新鮮さを保つ工夫が必要。長期の関係では、意図的に変化を作ることが鍵。',
    work:'トラベラー・フリーランス・営業・起業家・外交官など多様な環境で活躍。変化の多い職場環境が合っている。金運は「動くほど」増える。じっとしていると停滞する。',
    advice:'「一つのことを続ける」練習が、あなたの可能性を10倍にします。自由と責任はセットです。',
    compat: ['点火者', '洞察者'],
  },
  '調律者': {
    label:'✨ 調和設計型',
    color:'#a09030',
    tagline:'すべての音を、美しい和音に変える',
    desc:'バランス感覚と審美眼を持ち、対立を調和へと導く力があります。場の空気を読み、最適なタイミングで最適な言葉を選ぶ。',
    personality:'穏やかで公平。どんな立場の人とも良好な関係を築き、コンフリクトを避けながら解決に向かう。完璧主義的な側面もあり、細部へのこだわりが強い。美しいものに敏感で、環境が心に影響しやすい。',
    love:'恋愛は穏やかで安定している。刺激より安心を重視し、信頼関係をゆっくり築く。パートナーへの思いやりが深く、長続きする関係を作る。ただし、自分の気持ちを後回しにしすぎる傾向がある。',
    work:'調停者・外交官・デザイナー・音楽家・マネージャーなど。チームの調和を保ちながら成果を出す役割で光る。金運は「環境の美しさ」に比例する。整えられた空間が豊かさを呼ぶ。',
    advice:'「曖昧な返事」をやめることが、あなたの運気を開きます。自分の意見をはっきり伝えることで、本来の力が解放されます。',
    compat: ['表現者', '点火者'],
  },
};

function determineType(lifePath, el, kyusei, zodiac) {
  // Multi-factor scoring
  const scores = { '点火者':0, '包容者':0, '表現者':0, '洞察者':0, '解放者':0, '調律者':0 };

  // LifePath contribution
  const lpMap = {1:'点火者',2:'調律者',3:'表現者',4:'調律者',5:'解放者',6:'包容者',7:'洞察者',8:'点火者',9:'包容者',11:'洞察者',22:'点火者',33:'包容者'};
  if (lpMap[lifePath]) scores[lpMap[lifePath]] += 3;

  // Element contribution
  const elMap = {'木':'解放者','火':'点火者','土':'包容者','金':'洞察者','水':'洞察者'};
  if (elMap[el]) scores[elMap[el]] += 2;

  // Kyusei contribution
  const kyMap = {1:'洞察者',2:'包容者',3:'解放者',4:'表現者',5:'点火者',6:'調律者',7:'表現者',8:'調律者',9:'点火者'};
  if (kyMap[kyusei]) scores[kyMap[kyusei]] += 2;

  // Zodiac contribution
  const zodMap = {
    '牡羊座':'点火者','牡牛座':'調律者','双子座':'解放者','蟹座':'包容者',
    '獅子座':'表現者','乙女座':'洞察者','天秤座':'調律者','蠍座':'洞察者',
    '射手座':'解放者','山羊座':'点火者','水瓶座':'表現者','魚座':'包容者',
  };
  if (zodMap[zodiac.name]) scores[zodMap[zodiac.name]] += 2;

  return Object.entries(scores).sort((a,b)=>b[1]-a[1])[0][0];
}

// ═══ FORTUNE PHASES ═══
// スコアマッピングテーブル（2026-05-08 最適化）
const ELEMENT_SCORE = { '木':16, '火':18, '土':10, '金':12, '水':6 };
const KYUSEI_SCORE = { 1:10, 2:4, 3:16, 4:14, 5:20, 6:16, 7:12, 8:6, 9:18 };
const PERSONAL_MONTH_SCORE = { 1:18, 2:6, 3:16, 4:8, 5:14, 6:12, 7:4, 8:18, 9:14 };
const PERSONAL_YEAR_SCORE = { 1:20, 2:6, 3:16, 4:8, 5:14, 6:12, 7:4, 8:18, 9:14, 11:16, 22:18, 33:16 };
const MAYA_TONE_SCORE = { 1:18, 2:8, 3:14, 4:8, 5:16, 6:12, 7:18, 8:12, 9:18, 10:10, 11:6, 12:14, 13:16 };
const ZODIAC_SCORE = {
  '牡羊座':18,'獅子座':16,'射手座':14,'牡牛座':12,'乙女座':10,'山羊座':10,
  '双子座':16,'天秤座':14,'水瓶座':14,'蟹座':8,'蠍座':10,'魚座':8
};

// 数秘術：個人年数を計算
function calcPersonalYear(m, d, y) {
  const s = `${m}${d}${y}`.split('').reduce((a,b)=>a+parseInt(b),0);
  while (s > 9 && s !== 11 && s !== 22 && s !== 33) {
    return s.toString().split('').reduce((a,b)=>a+parseInt(b),0);
  }
  return s;
}

// スコアをフェーズに変換
function scoreToPhase(score) {
  if (score >= 16) return { phase:'春-始動期', emoji:'🌱', desc:'新しいことを始めるのに最適な時期。エネルギーが高く、チャンスが訪れやすい。積極的な行動が運を広げます。' };
  if (score >= 11) return { phase:'夏-拡大期', emoji:'🌿', desc:'活動や影響力を広げるのに良い時期。周囲との協力も進みやすく、成長が加速します。' };
  if (score >= 6) return { phase:'秋-収穫期', emoji:'🍂', desc:'これまでの努力が実を結ぶ時期。成果を受け取り、整理することが大切です。' };
  return { phase:'冬-調整期', emoji:'🌙', desc:'内面を整える大切な時期。焦らず、自分のペースで準備を進めることが運を開きます。' };
}

// 層2-1：年運計算（最適化版：スコアマッピング使用）
function calcYearFortune(ty, by, bm, bd, el, lifePath, kyusei, zodiac, maya) {
  const fourPillarsScore = ELEMENT_SCORE[el] || 12;
  const personalYear = calcPersonalYear(bm, bd, ty);
  const numerologyScore = PERSONAL_YEAR_SCORE[personalYear] || 12;
  const kyuseiYearScore = KYUSEI_SCORE[kyusei] || 12;
  const mayaScore = MAYA_TONE_SCORE[maya.toneNum] || 12;
  const zodiacScore = ZODIAC_SCORE[zodiac.name] || 12;
  const bioScore = 12;

  // より大きな分散を出すために、スコア範囲を拡大（0-20→0-24）してから正規化
  const expandedScore = Math.round(
    fourPillarsScore * 0.35 +
    numerologyScore * 0.22 +
    kyuseiYearScore * 0.27 +
    mayaScore * 0.10 +
    zodiacScore * 0.04 +
    bioScore * 0.02
  );

  // スコアを非線形に変換して分散を拡大
  const normalized = Math.max(0, Math.min(20, expandedScore));
  const dispersed = Math.round(((normalized - 12) * 1.8 + 12));
  const final = Math.max(0, Math.min(20, dispersed));

  return { score: final, ...scoreToPhase(final) };
}

// 月初日のバイオリズムスコア計算（0-20）
function getCalcBioMonthScore(by, bm, bd, ty, tm) {
  // 対象月の初日のバイオリズム（身体23日、感情28日、知性33日周期）を計算
  const bio = calcBio(by, bm, bd, ty, tm, 1);  // 月初日（1日）
  const avg = (bio.physical + bio.emotional + bio.intellectual) / 3;
  // バイオリズム平均値 (-1.0〜+1.0) を スコア (0〜20) に正規化
  return Math.max(0, Math.min(20, Math.round(avg * 10 + 10)));
}

// 層2-2：月運計算（最適化版：スコアマッピング使用）
function calcMonthFortune(ty, tm, by, bm, bd, el, lifePath, kyusei, zodiac, maya) {
  const personalMonth = ((tm + calcPersonalYear(bm, bd, ty)) % 9 || 9);
  const fourPillarsScore = ELEMENT_SCORE[el] || 12;
  const numerologyScore = PERSONAL_MONTH_SCORE[personalMonth] || 12;
  const kyuseiMonthScore = calcKyusei(ty, tm);
  const kyuseiScore = KYUSEI_SCORE[kyuseiMonthScore] || 12;
  const mayaScore = MAYA_TONE_SCORE[maya.toneNum] || 12;
  const bioMonthScore = getCalcBioMonthScore(by, bm, bd, ty, tm);
  const zodiacScore = ZODIAC_SCORE[zodiac.name] || 12;

  // より大きな分散を出すために、スコア範囲を拡大（0-20→0-24）してから正規化
  const expandedScore = Math.round(
    fourPillarsScore * 0.28 +
    kyuseiScore * 0.28 +
    numerologyScore * 0.18 +
    mayaScore * 0.12 +
    bioMonthScore * 0.10 +
    zodiacScore * 0.04
  );

  // スコアを非線形に変換して分散を拡大
  const normalized = Math.max(0, Math.min(20, expandedScore));
  const dispersed = Math.round(((normalized - 12) * 1.8 + 12));
  const final = Math.max(0, Math.min(20, dispersed));

  return { score: final, ...scoreToPhase(final) };
}

// 層3：今日の占い - 仕様の重み付け
function calcDayFortune(y, m, d, ty, tm, td, el, lifePath, kyusei, zodiac, maya) {
  const bio = calcBio(y, m, d, ty, tm, td);
  const bioScore = Math.round((bio.physical + bio.emotional + bio.intellectual) / 3 * 10 + 10);
  const normalizedBioScore = Math.max(0, Math.min(20, bioScore));

  const kyuseiDayScore = 12;
  const fourPillarsDayScore = 12;
  const numerologyDayScore = 11;
  const mayaDayScore = 12;
  const zodiacDayScore = 10;

  const score = Math.round(
    normalizedBioScore * 0.30 +
    kyuseiDayScore * 0.20 +
    fourPillarsDayScore * 0.20 +
    numerologyDayScore * 0.15 +
    mayaDayScore * 0.10 +
    zodiacDayScore * 0.05
  );

  const normalizedScore = Math.max(0, Math.min(20, score));
  const lucky = ((td + lifePath + kyusei) % 5 + 5) % 5;
  const luckyItems = [
    {color:'白', item:'白いハンカチ', number:'3', direction:'北'},
    {color:'金', item:'ゴールドのアクセサリー', number:'8', direction:'南'},
    {color:'緑', item:'植物・観葉植物', number:'4', direction:'東'},
    {color:'青', item:'水を入れたクリスタルグラス', number:'7', direction:'西'},
    {color:'紫', item:'アメジスト', number:'9', direction:'南東'},
  ][lucky];

  const lifePathHour = ((lifePath - 1) % 24); // lifePath を 0-23 の時刻に変換
  const actions = [
    `${ELEMENT_DATA[el]?.dir || '東'}の方角を向いて深呼吸を三回。${el}の気があなたを満たす。`,
    `${lifePath}という数字に縁のある時刻（${String(lifePathHour).padStart(2, '0')}時）に重要な決断を。`,
    `${KYUSEI_DIRS[kyusei-1]}方向にある場所で、大切な人と食事をすることで運気が上昇。`,
    `${zodiac.name}の特質を活かした行動が吉。今日は協調を心がけて。`,
    `今日の幸運色「${luckyItems.color}」を身につけることで、見えない加護を受け取る。`,
  ];
  const action = actions[(td + lifePath) % actions.length];
  return { score: normalizedScore, luckyItems, action, bio };
}

// 旧6タイプシステム用の相性計算（互換性維持）
function calcCompat(myType) {
  const typeData = SIX_TYPES[myType];
  if (!typeData) return [];
  return typeData.compat.map(t => ({ type: t, ...SIX_TYPES[t] }));
}

// ═══════════════════════════════════════════════════════
//  UI PRIMITIVES
// ═══════════════════════════════════════════════════════
const HexSymbol = ({ size=60, color='#c8a84b', animate=false }) => {
  const pts = Array.from({length:6},(_,i)=>{
    const a=(i*60-30)*Math.PI/180;
    return `${size/2+(size/2-4)*Math.cos(a)},${size/2+(size/2-4)*Math.sin(a)}`;
  }).join(' ');
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{display:'block'}}>
      <polygon points={pts} fill="none" stroke={color} strokeWidth="1"
        style={animate?{animation:'spin-slow 20s linear infinite',transformOrigin:'center'}:{}}/>
      <polygon points={pts} fill="none" stroke={color} strokeWidth="0.5" opacity="0.4"
        transform={`rotate(30,${size/2},${size/2}) scale(0.7) translate(${size*0.15},${size*0.15})`}/>
      <circle cx={size/2} cy={size/2} r="2" fill={color} opacity="0.8"/>
    </svg>
  );
};

const OrbitalRing = ({ size=120 }) => (
  <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}
    style={{display:'block',position:'absolute',top:'50%',left:'50%',transform:'translate(-50%,-50%)'}}>
    <circle cx={size/2} cy={size/2} r={size/2-8} fill="none" stroke="rgba(200,168,75,0.12)" strokeWidth="1"
      strokeDasharray="4 6" style={{animation:'spin-slow 30s linear infinite',transformOrigin:'center'}}/>
    <circle cx={size/2} cy={size/2} r={size/2-20} fill="none" stroke="rgba(90,158,138,0.1)" strokeWidth="1"
      strokeDasharray="2 8" style={{animation:'spin-rev 20s linear infinite',transformOrigin:'center'}}/>
  </svg>
);

const GoldDivider = ({delay=0}) => (
  <div style={{height:'1px',background:'linear-gradient(90deg,transparent,var(--gold-dim),rgba(200,168,75,0.6),var(--gold-dim),transparent)',
    animation:`expand-line 0.8s ease ${delay}s both`}}/>
);

const ScoreDots = ({ score, max=10, color='#c8a84b' }) => (
  <div style={{display:'flex',gap:'4px',alignItems:'center'}}>
    {Array.from({length:max},(_,i)=>(
      <div key={i} style={{width:'6px',height:'6px',borderRadius:'50%',
        background: i<score ? color : 'rgba(255,255,255,0.08)',
        boxShadow: i<score ? `0 0 6px ${color}80` : 'none',
        transition:`all 0.3s ease ${i*0.04}s`}}/>
    ))}
  </div>
);

const BioChart = ({ data, delay=0 }) => {
  const W=280,H=80,mid=H/2,pts=40;
  const makePath=(period,color)=>{
    const d=Array.from({length:pts},(_,i)=>{
      const x=(i/(pts-1))*W;
      const dy=data.days-20+(i/(pts-1))*40;
      const yy=mid-Math.sin(2*Math.PI*dy/period)*(mid-8);
      return `${i===0?'M':'L'} ${x.toFixed(1)} ${yy.toFixed(1)}`;
    }).join(' ');
    return <path d={d} fill="none" stroke={color} strokeWidth="1.5" opacity="0.85"/>;
  };
  return (
    <div style={{opacity:0,animation:`fadeIn 0.6s ease ${delay}s forwards`}}>
      <svg width={W} height={H} viewBox={`0 0 ${W} ${H}`} style={{overflow:'visible',display:'block',margin:'0 auto'}}>
        <line x1="0" y1={mid} x2={W} y2={mid} stroke="rgba(200,168,75,0.15)" strokeWidth="1"/>
        <line x1={W/2} y1="0" x2={W/2} y2={H} stroke="rgba(200,168,75,0.3)" strokeWidth="1" strokeDasharray="3 3"/>
        {makePath(23,'#c8a84b')}{makePath(28,'#5a9e8a')}{makePath(33,'#8080c0')}
        <circle cx={W/2} cy={mid-Math.sin(2*Math.PI*data.days/23)*(mid-8)} r="3" fill="#c8a84b"/>
        <circle cx={W/2} cy={mid-Math.sin(2*Math.PI*data.days/28)*(mid-8)} r="3" fill="#5a9e8a"/>
        <circle cx={W/2} cy={mid-Math.sin(2*Math.PI*data.days/33)*(mid-8)} r="3" fill="#8080c0"/>
        <text x={W/2} y={H+14} textAnchor="middle" fill="rgba(200,168,75,0.5)" fontSize="9" fontFamily="var(--serif-en)">TODAY</text>
      </svg>
      <div style={{display:'flex',gap:'16px',justifyContent:'center',marginTop:'12px'}}>
        {[{label:'肉体',v:data.physical,color:'#c8a84b'},{label:'感情',v:data.emotional,color:'#5a9e8a'},{label:'知性',v:data.intellectual,color:'#8080c0'}].map(({label,v,color})=>(
          <div key={label} style={{display:'flex',flexDirection:'column',alignItems:'center',gap:'4px'}}>
            <span style={{fontSize:'0.65rem',color:'var(--text-dim)',letterSpacing:'0.1em'}}>{label}</span>
            <div style={{width:48,height:4,background:'rgba(255,255,255,0.08)',borderRadius:'2px',overflow:'hidden'}}>
              <div style={{height:'100%',borderRadius:'2px',background:color,width:`${Math.abs(v)*100}%`,opacity:v>0?1:0.4}}/>
            </div>
            <span style={{fontSize:'0.7rem',color}}>{v>0.3?'↑高':v<-0.3?'↓低':'→中'}</span>
          </div>
        ))}
      </div>
    </div>
  );
};

// ═══ EXPANDABLE CARD ═══
const ReadingCard = ({ index, title, subtitle, system, icon, children, delay=0, accentColor='var(--gold)', defaultOpen=false }) => {
  const [open,setOpen] = React.useState(defaultOpen);
  return (
    <div onClick={()=>setOpen(!open)} style={{
      background:'linear-gradient(135deg,rgba(16,16,28,0.95),rgba(10,10,18,0.98))',
      border:`1px solid ${open ? accentColor+'44':'var(--border)'}`,
      borderRadius:'2px',padding:'20px 24px',cursor:'pointer',
      transition:'all 0.4s ease',
      opacity:0,animation:`reveal-card 0.7s ease ${delay}s forwards`,
      boxShadow:open?`0 0 40px ${accentColor}18,inset 0 0 60px rgba(0,0,0,0.3)`:'0 4px 24px rgba(0,0,0,0.4)',
      position:'relative',overflow:'hidden',
    }}>
      <div style={{position:'absolute',top:0,left:0,width:'30px',height:'30px',borderTop:`1px solid ${accentColor}60`,borderLeft:`1px solid ${accentColor}60`}}/>
      <div style={{position:'absolute',bottom:0,right:0,width:'30px',height:'30px',borderBottom:`1px solid ${accentColor}60`,borderRight:`1px solid ${accentColor}60`}}/>
      <div style={{display:'flex',alignItems:'center',gap:'14px'}}>
        <div style={{width:'40px',height:'40px',borderRadius:'50%',
          background:`radial-gradient(circle at 40% 40%,${accentColor}20,transparent)`,
          border:`1px solid ${accentColor}40`,
          display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0,
          fontSize:'1rem',color:accentColor,fontFamily:'var(--serif-jp)'}}>
          {icon}
        </div>
        <div style={{flex:1,minWidth:0}}>
          <div style={{display:'flex',alignItems:'center',gap:'8px',flexWrap:'wrap'}}>
            <span style={{fontSize:'0.58rem',color:accentColor,letterSpacing:'0.2em',fontFamily:'var(--serif-en)',opacity:0.7,textTransform:'uppercase'}}>命 {index}</span>
            <span style={{fontSize:'0.58rem',color:'var(--text-dim)',letterSpacing:'0.1em'}}>{system}</span>
          </div>
          <div style={{display:'flex',alignItems:'baseline',gap:'8px',flexWrap:'wrap'}}>
            <h3 style={{fontSize:'0.95rem',fontWeight:500,color:'var(--text)',letterSpacing:'0.05em'}}>{title}</h3>
            {subtitle&&<span style={{fontSize:'0.75rem',color:accentColor,fontFamily:'var(--serif-en)',fontStyle:'italic'}}>{subtitle}</span>}
          </div>
        </div>
        <div style={{flexShrink:0,color:accentColor,fontSize:'0.8rem',transform:open?'rotate(180deg)':'rotate(0)',transition:'transform 0.3s ease',opacity:0.6}}>▾</div>
      </div>
      {open&&(
        <div style={{marginTop:'18px',paddingTop:'18px',borderTop:`1px solid ${accentColor}20`,animation:'fadeIn 0.3s ease'}}>
          {children}
        </div>
      )}
    </div>
  );
};

// ═══ SECTION HEADER ═══
const SectionHeader = ({ num, label, sub, delay=0 }) => (
  <div style={{opacity:0,animation:`fadeUp 0.7s ease ${delay}s forwards`,marginBottom:'20px'}}>
    <div style={{display:'flex',alignItems:'center',gap:'16px'}}>
      <div style={{width:'36px',height:'36px',border:'1px solid var(--gold-dim)',
        display:'flex',alignItems:'center',justifyContent:'center',
        background:'rgba(200,168,75,0.05)',flexShrink:0}}>
        <span style={{fontSize:'0.8rem',color:'var(--gold)',fontFamily:'var(--serif-en)'}}>{num}</span>
      </div>
      <div>
        <div style={{fontSize:'1rem',color:'var(--text)',letterSpacing:'0.15em',fontWeight:500}}>{label}</div>
        {sub&&<div style={{fontSize:'0.65rem',color:'var(--text-dim)',letterSpacing:'0.1em',marginTop:'2px'}}>{sub}</div>}
      </div>
    </div>
    <div style={{marginTop:'12px'}}><GoldDivider delay={delay+0.1}/></div>
  </div>
);

// ═══ LOADING ═══
const LoadingOracle = ({ onComplete }) => {
  const [step,setStep] = React.useState(0);
  const steps=['命盤を展開中…','星図を照合中…','運気波動を計算中…','六タイプを判定中…','マヤ暦と同調中…','六命を統合中…'];
  React.useEffect(()=>{
    const timers=steps.map((_,i)=>setTimeout(()=>setStep(i+1),i*550+350));
    const done=setTimeout(onComplete,steps.length*550+700);
    return()=>{timers.forEach(clearTimeout);clearTimeout(done);};
  },[]);
  return (
    <div style={{display:'flex',flexDirection:'column',alignItems:'center',justifyContent:'center',minHeight:'100vh',gap:'32px'}}>
      <div style={{position:'relative',width:'120px',height:'120px',display:'flex',alignItems:'center',justifyContent:'center'}}>
        <OrbitalRing size={120}/><HexSymbol size={50} color="#c8a84b" animate/>
      </div>
      <div style={{display:'flex',flexDirection:'column',gap:'10px',width:'220px'}}>
        {steps.map((s,i)=>(
          <div key={i} style={{display:'flex',alignItems:'center',gap:'10px',opacity:step>i?1:0.2,transition:'opacity 0.4s ease'}}>
            <div style={{width:'6px',height:'6px',borderRadius:'50%',background:step>i?'var(--gold)':'var(--border)',
              flexShrink:0,transition:'background 0.3s ease',boxShadow:step>i?'0 0 8px var(--gold)':'none'}}/>
            <span style={{fontSize:'0.75rem',color:'var(--text-dim)',letterSpacing:'0.1em'}}>{s}</span>
          </div>
        ))}
      </div>
    </div>
  );
};

// ═══ HERO SCREEN ═══
const HeroScreen = ({ onSubmit, isLoggedIn, userBirth, userTime, userBirthLatitude, userBirthLongitude, userName, onLoginClick, onRegisterClick, onLogoutClick, onMyPageClick, preselectedTargetDate, onSelectCelebrity }) => {
  const today = new Date();
  const todayStr = `${today.getFullYear()}-${String(today.getMonth()+1).padStart(2,'0')}-${String(today.getDate()).padStart(2,'0')}`;

  const [birth, setBirth] = React.useState(isLoggedIn && userBirth ? userBirth : '');
  const [time,  setTime]  = React.useState(isLoggedIn && userTime  ? formatHourInputValue(userTime)  : '');
  const [birthplace, setBirthplace] = React.useState(isLoggedIn ? formatBirthLatLngValue(userBirthLatitude, userBirthLongitude) : '');
  const [targetDate, setTargetDate] = React.useState(todayStr);
  const [err,  setErr]   = React.useState('');
  const [focusedField, setFocused] = React.useState(null);
  const [featuredCelebrities, setFeaturedCelebrities] = React.useState([]);
  const [celebritySamples, setCelebritySamples] = React.useState([]);
  const formRef = React.useRef(null);

  React.useEffect(() => {
    if (isLoggedIn) {
      setBirth(userBirth || '');
      setTime(formatHourInputValue(userTime || ''));
      setBirthplace(formatBirthLatLngValue(userBirthLatitude, userBirthLongitude));
    } else {
      setBirth('');
      setTime('');
      setBirthplace('');
      setTargetDate(todayStr);
    }
  }, [isLoggedIn, userBirth, userTime, userBirthLatitude, userBirthLongitude, todayStr]);

  React.useEffect(() => {
    if (isLoggedIn && preselectedTargetDate) {
      setTargetDate(preselectedTargetDate);
    }
  }, [isLoggedIn, preselectedTargetDate]);

  React.useEffect(() => {
    fetch('api/get_featured_celebrities.php?limit=4')
      .then(r => r.json())
      .then(data => {
        if (data.status === 'success' && data.data) {
          setFeaturedCelebrities(data.data);
        }
      })
      .catch(err => console.error('Featured celebrities API error:', err));
  }, []);

  React.useEffect(() => {
    console.log('Fetching celebrity samples...');
    fetch('./api/fortune.php?action=get_celebrity_samples')
      .then(r => r.json())
      .then(data => {
        console.log('Celebrity samples response:', data);
        if (data.success && data.samples) {
          console.log('Setting celebrity samples:', data.samples);
          setCelebritySamples(data.samples);
        } else {
          console.warn('Invalid response structure:', data);
        }
      })
      .catch(err => console.error('Celebrity samples API error:', err));
  }, []);

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!birth) { setErr('生年月日を入力してください'); return; }
    setErr('');
    const parsedBirthplace = parseBirthLatLngValue(birthplace);
    onSubmit(birth, time, isTimeMachine ? targetDate : null, {
      birthLatitude: parsedBirthplace.birthLatitude,
      birthLongitude: parsedBirthplace.birthLongitude,
    });
  };

  const isTimeMachine = targetDate && targetDate !== todayStr;
  const formatTargetDate = (str) => {
    if (!str) return '';
    const d = new Date(str);
    return `${d.getFullYear()}年${d.getMonth()+1}月${d.getDate()}日`;
  };

  const applySampleBirthDate = (sampleBirthDate) => {
    if (!sampleBirthDate) return;
    setBirth(sampleBirthDate);
    setErr('');
    formRef.current?.scrollIntoView({ behavior:'smooth', block:'center' });
  };

  const applySampleEventDate = (sampleBirthDate, eventDate) => {
    if (sampleBirthDate) {
      setBirth(sampleBirthDate);
    }
    if (eventDate) {
      setTargetDate(eventDate);
    }
    setErr('');
    formRef.current?.scrollIntoView({ behavior:'smooth', block:'center' });
  };

  const linkButtonStyle = {
    background:'none',
    border:'none',
    padding:0,
    color:'var(--gold)',
    textDecoration:'none',
    cursor:'pointer',
    font:'inherit',
    fontFamily:'inherit',
  };

  const inputStyle = (id) => ({
    width:'100%',maxWidth:'100%',padding:'12px 14px',
    background:'rgba(255,255,255,0.03)',
    border:`1px solid ${focusedField===id?'rgba(200,168,75,0.5)':'var(--border)'}`,
    color:'var(--text)',fontSize:'0.95rem',fontFamily:'var(--serif-en)',
    letterSpacing:'0.1em',outline:'none',textAlign:'center',
    transition:'border-color 0.3s ease',colorScheme:'dark',borderRadius:'2px',
    boxSizing:'border-box',minWidth:0,
  });

  const [isSmallScreen, setIsSmallScreen] = React.useState(window.innerWidth <= 768);
  React.useEffect(() => {
    const handleResize = () => setIsSmallScreen(window.innerWidth <= 768);
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  return (
    <div style={{minHeight:'100vh',position:'relative',display:'flex',flexDirection:'column',alignItems:'center',justifyContent:'center',padding:'40px max(12px, 5vw) 80px'}}>

      {/* Header */}
      {isSmallScreen && (
        <div style={{
          display:'flex',
          flexDirection:'column',
          alignItems:'flex-end',
          justifyContent:'space-between',
          marginBottom:'32px',opacity:0,animation:'fadeIn 0.6s ease 0.1s forwards',
          gap:'20px',
          width:'100%',
        }}>
          {/* Auth buttons - ログイン時のみ表示 */}
          {isLoggedIn && (
            <div style={{
              display:'flex',
              width:'100%',
              justifyContent:'flex-end',
              order:-2,
              gap:'8px',
            }}>
              <div style={{display:'flex',gap:'8px'}}>
                <button onClick={onMyPageClick} style={{
                  background:'none',border:'1px solid var(--border)',color:'var(--text-dim)',
                  padding:'5px 12px',fontSize:'0.62rem',letterSpacing:'0.1em',
                  fontFamily:'var(--serif-jp)',cursor:'pointer',borderRadius:'2px',transition:'all 0.2s ease',
                }}
                  onMouseEnter={e=>{e.currentTarget.style.borderColor='var(--gold-dim)';e.currentTarget.style.color='var(--gold)';}}
                  onMouseLeave={e=>{e.currentTarget.style.borderColor='var(--border)';e.currentTarget.style.color='var(--text-dim)';}}>
                  マイページ
                </button>
                <button onClick={onLogoutClick} style={{
                  background:'none',border:'1px solid var(--border)',color:'var(--text-dim)',
                  padding:'5px 12px',fontSize:'0.62rem',letterSpacing:'0.1em',
                  fontFamily:'var(--serif-jp)',cursor:'pointer',borderRadius:'2px',transition:'all 0.2s ease',
                }}
                  onMouseEnter={e=>{e.currentTarget.style.borderColor='var(--gold-dim)';e.currentTarget.style.color='var(--gold)';}}
                  onMouseLeave={e=>{e.currentTarget.style.borderColor='var(--border)';e.currentTarget.style.color='var(--text-dim)';}}>
                  ログアウト
                </button>
              </div>
            </div>
          )}

          {/* ユーザー名 - 2番目に表示 */}
          {isLoggedIn && (
            <div style={{
              width:'100%',
              textAlign:'right',
              order:-1,
            }}>
              <span style={{fontSize:'0.65rem',color:'var(--gold)',letterSpacing:'0.08em'}}>{userName || 'ユーザー'} 様</span>
            </div>
          )}

          {/* Brand - スマホはセンター寄せ、一番下 */}
          <div style={{
            flex:'none',
            textAlign:'center',
            width:'100%',
            order:0,
          }}>
            <div style={{fontSize:'0.55rem',letterSpacing:'0.35em',color:'var(--gold)',fontFamily:'var(--serif-en)',textTransform:'uppercase',opacity:0.7,marginBottom:'3px'}}>Life Code Reading</div>
            <div style={{fontSize:'1.2rem',fontWeight:300,letterSpacing:'0.25em',
              background:'linear-gradient(180deg,rgba(232,204,128,0.95) 0%,rgba(200,168,75,0.7) 100%)',
              WebkitBackgroundClip:'text',WebkitTextFillColor:'transparent',backgroundClip:'text'}}>六命解析</div>
          </div>
        </div>
      )}

      {/* PC Header */}
      {!isSmallScreen && (
        <div style={{
          display:'flex',
          flexDirection:'column',
          alignItems:'flex-end',
          marginBottom:'32px',opacity:0,animation:'fadeIn 0.6s ease 0.1s forwards',
          gap:'12px',
          width:'100%',
        }}>
          {/* Auth buttons - ログイン時のみ表示 */}
          {isLoggedIn && (
            <div style={{display:'flex',gap:'8px'}}>
              <div style={{display:'flex',gap:'8px'}}>
                <button onClick={onMyPageClick} style={{
                  background:'none',border:'1px solid var(--border)',color:'var(--text-dim)',
                  padding:'5px 12px',fontSize:'0.62rem',letterSpacing:'0.1em',
                  fontFamily:'var(--serif-jp)',cursor:'pointer',borderRadius:'2px',transition:'all 0.2s ease',
                }}
                  onMouseEnter={e=>{e.currentTarget.style.borderColor='var(--gold-dim)';e.currentTarget.style.color='var(--gold)';}}
                  onMouseLeave={e=>{e.currentTarget.style.borderColor='var(--border)';e.currentTarget.style.color='var(--text-dim)';}}>
                  マイページ
                </button>
                <button onClick={onLogoutClick} style={{
                  background:'none',border:'1px solid var(--border)',color:'var(--text-dim)',
                  padding:'5px 12px',fontSize:'0.62rem',letterSpacing:'0.1em',
                  fontFamily:'var(--serif-jp)',cursor:'pointer',borderRadius:'2px',transition:'all 0.2s ease',
                }}
                  onMouseEnter={e=>{e.currentTarget.style.borderColor='var(--gold-dim)';e.currentTarget.style.color='var(--gold)';}}
                  onMouseLeave={e=>{e.currentTarget.style.borderColor='var(--border)';e.currentTarget.style.color='var(--text-dim)';}}>
                  ログアウト
                </button>
              </div>
            </div>
          )}

          {/* ユーザー名 - 下に表示 */}
          {isLoggedIn && (
            <div style={{width:'100%',textAlign:'right'}}>
              <span style={{fontSize:'0.65rem',color:'var(--gold)',letterSpacing:'0.08em'}}>{userName || 'ユーザー'} 様</span>
            </div>
          )}
        </div>
      )}


      <div style={{marginBottom:'36px',opacity:0,animation:'fadeIn 1.2s ease 0.2s forwards'}}>
        <div style={{position:'relative',width:'90px',height:'90px',margin:'0 auto',display:'flex',alignItems:'center',justifyContent:'center'}}>
          <OrbitalRing size={90}/><HexSymbol size={38} color="#c8a84b" animate/>
        </div>
      </div>
      <div style={{textAlign:'center',marginBottom:'12px',opacity:0,animation:'fadeUp 0.9s ease 0.4s forwards'}}>
        <div style={{fontSize:'0.62rem',letterSpacing:'0.4em',color:'var(--gold)',fontFamily:'var(--serif-en)',textTransform:'uppercase',marginBottom:'12px',opacity:0.8}}>Life Code Reading</div>
        <h1 style={{fontSize:'clamp(2.4rem,6vw,3.6rem)',fontWeight:300,letterSpacing:'0.3em',lineHeight:1.2,
          background:'linear-gradient(180deg,rgba(232,204,128,0.95) 0%,rgba(200,168,75,0.7) 100%)',
          WebkitBackgroundClip:'text',WebkitTextFillColor:'transparent',backgroundClip:'text'}}>六命解析</h1>
      </div>
      <div style={{width:'180px',margin:'0 auto 32px',opacity:0,animation:'fadeIn 0.8s ease 0.7s forwards'}}>
        <GoldDivider/>
      </div>
      <p style={{fontSize:'0.78rem',color:'var(--text-dim)',lineHeight:2,letterSpacing:'0.12em',textAlign:'center',maxWidth:'360px',
        opacity:0,animation:'fadeUp 0.8s ease 0.9s forwards'}}>
        生年月日に刻まれた六つの命の傾向を<br/>古典占術と宇宙のリズムで解き明かす
      </p>
      <p style={{fontSize:'0.7rem',color:'var(--text-dim)',lineHeight:1.8,letterSpacing:'0.1em',textAlign:'center',maxWidth:'400px',
        opacity:0,animation:'fadeUp 0.8s ease 1.0s forwards',marginTop:'28px',marginBottom:'36px',fontWeight:300}}>
        「あの人の転機」は、運気の流れと重なっていたのか？<br/>六命解析では、著名人の人生イベントをバックテスト。起業、転職、受賞、記録達成などの出来事を、過去の運気スコアと照合しました。
      </p>

      {featuredCelebrities.length > 0 && (
        <div style={{width:'100%',maxWidth:'500px',margin:'32px auto 0',opacity:0,animation:'fadeUp 0.8s ease 1.2s forwards'}}>
          <p style={{fontSize:'0.62rem',letterSpacing:'0.15em',color:'var(--gold)',textAlign:'center',marginBottom:'16px',fontWeight:600}}>
            占い精度を検証した著名人たち
          </p>
          <div style={{display:'flex',flexDirection:'column',gap:'12px'}}>
            {featuredCelebrities.map((celeb, idx) => (
              <div key={celeb.id} style={{
                padding:'12px 14px',
                border:'1px solid var(--border)',
                borderRadius:'3px',
                fontSize:'0.68rem',
                background:'rgba(255,255,255,0.01)',
                transition:'all 0.2s ease',
                cursor:'pointer',
              }}
              onClick={() => onSelectCelebrity && onSelectCelebrity(celeb)}
              onMouseEnter={e => {e.currentTarget.style.borderColor='var(--gold)';e.currentTarget.style.background='rgba(200,168,75,0.05)';}}
              onMouseLeave={e => {e.currentTarget.style.borderColor='var(--border)';e.currentTarget.style.background='rgba(255,255,255,0.01)';}}>
                <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:'6px'}}>
                  <span style={{fontWeight:600,color:'var(--text-main)'}}>{celeb.name}</span>
                  <span style={{
                    color: celeb.accuracy >= 80 ? '#c8a84b' : '#5a9e8a',
                    fontWeight:600
                  }}>
                    {Math.round(celeb.accuracy)}%
                  </span>
                </div>
                <div style={{color:'var(--text-dim)',fontSize:'0.65rem',marginBottom:'4px'}}>
                  {celeb.occupation_display || celeb.occupation || '肩書き情報なし'} • {celeb.matched_count}/{celeb.total_tests}件一致
                </div>
                {celeb.sample_events.length > 0 && (
                  <div style={{marginTop:'4px',display:'flex',flexWrap:'wrap',gap:'6px',alignItems:'center'}}>
                    <span style={{color:'var(--text-dim)',fontSize:'0.63rem',fontStyle:'italic'}}>
                      例：{celeb.sample_events[0].title}
                    </span>
                    {getTransitionBucketMeta(celeb.sample_events[0]) && (
                      <span style={{
                        fontSize:'0.6rem',
                        padding:'2px 6px',
                        border:'1px solid var(--border)',
                        borderRadius:'4px',
                        color:getTransitionBucketMeta(celeb.sample_events[0]).tone === 'high' ? '#c8a84b' : 'var(--text-dim)',
                        background:'rgba(255,255,255,0.02)'
                      }}>
                        {getTransitionBucketMeta(celeb.sample_events[0]).label}
                      </span>
                    )}
                  </div>
                )}
              </div>
            ))}
          </div>
        </div>
      )}

      {/* 有名人診断サンプル（複数著名人対応） */}
      {celebritySamples.length > 0 && (
        <div style={{width:'100%',margin:'40px auto 0',opacity:0,animation:'fadeUp 0.8s ease 1.2s forwards'}}>
          <p style={{fontSize:'0.62rem',letterSpacing:'0.15em',color:'var(--gold)',textAlign:'center',marginBottom:'20px',fontWeight:600}}>
            有名人の診断例
          </p>
          <div style={{
            display:'grid',
            gridTemplateColumns:isSmallScreen ? '1fr' : 'repeat(2, 1fr)',
            gap:'20px',
            maxWidth:'900px',
            margin:'0 auto',
            padding:'0 12px',
          }}>
            {celebritySamples.map((sample, idx) => {
              return (
                <div key={idx} style={{
                  padding:'16px',
                  border:'1px solid var(--border)',
                  borderRadius:'4px',
                  background:'rgba(255,255,255,0.02)',
                  transition:'all 0.2s ease',
                  display:'flex',
                  flexDirection:'column',
                }}>
                  <div style={{marginBottom:'12px'}}>
                    <h4 style={{fontSize:'0.9rem',fontWeight:600,color:'var(--gold)',margin:'0 0 6px 0'}}>{sample.name}</h4>
                    <div style={{fontSize:'0.65rem',color:'var(--text-dim)',display:'flex',flexDirection:'column',gap:'2px'}}>
                      <div>
                        <span style={{fontWeight:600}}>生年月日：</span>
                        <button type="button" onClick={()=>applySampleBirthDate(sample.birth_date)} style={linkButtonStyle} title="この生年月日を入力する">{sample.birth_date}</button>
                      </div>
                      <div><span>{sample.nine_star_name || '星不明'}</span></div>
                    </div>
                  </div>

                  <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:'10px',paddingBottom:'8px',borderBottom:'1px solid rgba(200,168,75,0.1)'}}>
                    <div>
                      <div style={{fontSize:'0.6rem',color:'var(--text-dim)',marginBottom:'2px'}}>的中率</div>
                      <div style={{fontSize:'1rem',fontWeight:600,color:'#c8a84b'}}>{sample.accuracy || 0}%</div>
                    </div>
                    <div>
                      <div style={{fontSize:'0.6rem',color:'var(--text-dim)',marginBottom:'2px'}}>テスト</div>
                      <div style={{fontSize:'0.9rem',fontWeight:500,color:'var(--text-main)'}}>{sample.event_count || 0}件</div>
                    </div>
                  </div>

                  {sample.events && sample.events.length > 0 && (
                    <div style={{fontSize:'0.65rem',color:'var(--text-dim)',flex:1}}>
                      <p style={{margin:'0 0 8px 0',fontSize:'0.6rem',fontWeight:600,color:'var(--gold)'}}>検証イベント（{sample.events.length}件表示）</p>
                      {sample.events.map((evt, i) => (
                        <div key={i} style={{marginBottom:'8px',paddingBottom:'6px',borderBottom:'1px solid rgba(200,168,75,0.05)'}}>
                          <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-start',marginBottom:'3px',gap:'8px'}}>
                            <span style={{fontWeight:500,flex:1,overflow:'hidden',textOverflow:'ellipsis'}}>{evt.title}</span>
                            <span style={{fontSize:'0.6rem',color:evt.matched === '✓' ? '#c8a84b' : '#a0a0a0',fontWeight:600,flexShrink:0}}>{evt.matched}</span>
                          </div>
                          <div style={{fontSize:'0.58rem',color:'var(--text-dim)'}}>
                            <button type="button" onClick={()=>applySampleEventDate(sample.birth_date, evt.date)} style={linkButtonStyle} title={`${evt.date}のタイムマシンを開く`}>{evt.date}</button>
                            <span style={{color:evt.polarity === 'positive' ? 'var(--text-dim)' : 'var(--text-dim)'}}>
                              {evt.polarity === 'positive' ? ' (好調)' : ' (低迷)'}
                            </span>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </div>
      )}

      <div style={{display:'flex',flexWrap:'wrap',gap:'7px',justifyContent:'center',margin:'24px 0 36px',
        opacity:0,animation:'fadeIn 0.8s ease 1.1s forwards',maxWidth:'380px'}}>
        {['四柱推命','数秘術','九星気学','12星座','バイオリズム','マヤ暦'].map(s=>(
          <span key={s} style={{padding:'3px 10px',border:'1px solid var(--border)',fontSize:'0.62rem',letterSpacing:'0.1em',color:'var(--text-dim)',background:'rgba(255,255,255,0.02)'}}>{s}</span>
        ))}
      </div>

      <form ref={formRef} onSubmit={handleSubmit} style={{display:'flex',flexDirection:'column',alignItems:'center',gap:'14px',width:'100%',maxWidth:'320px',opacity:0,animation:'fadeUp 0.9s ease 1.3s forwards',overflow:'hidden'}}>
        <div style={{width:'100%'}}>
          <label style={{display:'block',fontSize:'0.62rem',letterSpacing:'0.2em',color:'var(--text-dim)',marginBottom:'8px',textAlign:'center'}}>生年月日 *</label>
          <input type="date" value={birth} onChange={e=>setBirth(e.target.value)}
            onFocus={()=>setFocused('date')} onBlur={()=>setFocused(null)}
            min="1900-01-01" max="2025-12-31" style={inputStyle('date')}/>
        </div>
        <div style={{width:'100%'}}>
          <label style={{display:'block',fontSize:'0.62rem',letterSpacing:'0.2em',color:'var(--text-dim)',marginBottom:'8px',textAlign:'center'}}>生まれた時間（0〜23時・任意）</label>
          <input
            type="number"
            inputMode="numeric"
            min="0"
            max="23"
            step="1"
            value={time}
            onChange={e=>setTime(e.target.value)}
            onFocus={()=>setFocused('time')}
            onBlur={()=>setFocused(null)}
            style={inputStyle('time')}
            placeholder="12"
          />
          <div style={{fontSize:'0.58rem',color:'var(--text-dim)',textAlign:'center',marginTop:'6px',letterSpacing:'0.08em'}}>
            分は不要です。保存時は 00 分 00 秒として扱います
          </div>
          <div style={{fontSize:'0.58rem',color:'var(--text-dim)',textAlign:'center',marginTop:'6px',letterSpacing:'0.08em'}}>
            {isLoggedIn ? `ログイン中の生年月日: ${userBirth || '未登録'}` : 'ログイン中でなくても入力できます'}
          </div>
        </div>
        <div style={{width:'100%'}}>
          <label style={{display:'block',fontSize:'0.62rem',letterSpacing:'0.2em',color:'var(--text-dim)',marginBottom:'8px',textAlign:'center'}}>
            出生地 <span style={{color:'var(--gold)',opacity:0.5}}>(任意)</span>
          </label>
          <input
            type="text"
            value={birthplace}
            onChange={e=>setBirthplace(e.target.value)}
            onFocus={()=>setFocused('birthplace')}
            onBlur={()=>setFocused(null)}
            style={inputStyle('birthplace')}
            placeholder="35.681236, 139.767125"
          />
          <div style={{fontSize:'0.58rem',color:'var(--text-dim)',textAlign:'center',marginTop:'6px',letterSpacing:'0.08em'}}>
            緯度と経度を 1 行で入力できます。Google の座標をそのまま貼り付けても構いません。
          </div>
        </div>

        {/* ⏳ タイムマシン */}
        <div style={{width:'100%',animation:'fadeIn 0.4s ease'}}>
          <div style={{
            borderTop:'1px solid var(--border)',
            paddingTop:'16px',
          }}>
            <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:'10px'}}>
              <label style={{fontSize:'0.62rem',letterSpacing:'0.2em',color:isTimeMachine?'var(--gold)':'var(--text-dim)'}}>
                {isTimeMachine ? '⏳ タイムマシン稼働中' : '📅 診断する日付'}
              </label>
              {isTimeMachine && (
                <button type="button" onClick={()=>setTargetDate(todayStr)} style={{
                  background:'none',border:'none',fontSize:'0.6rem',color:'var(--text-dim)',
                  cursor:'pointer',letterSpacing:'0.08em',transition:'color 0.2s',padding:0,fontFamily:'var(--serif-jp)',
                }}
                  onMouseEnter={e=>e.currentTarget.style.color='var(--gold)'}
                  onMouseLeave={e=>e.currentTarget.style.color='var(--text-dim)'}>
                  今日に戻す
                </button>
              )}
            </div>
            <input type="date" value={targetDate} onChange={e=>setTargetDate(e.target.value)}
              onFocus={()=>setFocused('target')} onBlur={()=>setFocused(null)}
              min="1900-01-01" max="2099-12-31"
              style={{
                ...inputStyle('target'),
                border:`1px solid ${isTimeMachine?'rgba(200,168,75,0.5)':focusedField==='target'?'rgba(200,168,75,0.4)':'var(--border)'}`,
                background: isTimeMachine?'rgba(200,168,75,0.06)':'rgba(255,255,255,0.03)',
                color: isTimeMachine?'var(--gold-light)':'var(--text)',
              }}/>
            {isTimeMachine && (
              <div style={{
                fontSize:'0.68rem',color:'var(--gold)',textAlign:'center',
                marginTop:'8px',letterSpacing:'0.1em',
                animation:'fadeIn 0.3s ease',
              }}>
                {formatTargetDate(targetDate)} の運勢を解析します
              </div>
            )}
            {!isTimeMachine && (
              <div style={{fontSize:'0.58rem',color:'var(--text-dim)',textAlign:'center',marginTop:'6px',letterSpacing:'0.08em'}}>
                日付を変えると過去・未来の運勢を確認できます
              </div>
            )}
          </div>
        </div>
        {err&&<p style={{fontSize:'0.72rem',color:'var(--crimson)',letterSpacing:'0.1em'}}>{err}</p>}
        <button type="submit" style={{width:'100%',maxWidth:'100%',padding:'14px',boxSizing:'border-box',
          background:'linear-gradient(135deg,rgba(200,168,75,0.12),rgba(200,168,75,0.06))',
          border:'1px solid var(--gold-dim)',color:'var(--gold-light)',
          fontSize:'0.82rem',letterSpacing:'0.25em',fontFamily:'var(--serif-jp)',
          cursor:'pointer',transition:'all 0.3s ease',borderRadius:'2px'}}
          onMouseEnter={e=>{e.currentTarget.style.background='linear-gradient(135deg,rgba(200,168,75,0.22),rgba(200,168,75,0.12))';e.currentTarget.style.boxShadow='0 0 30px rgba(200,168,75,0.15)';}}
          onMouseLeave={e=>{e.currentTarget.style.background='linear-gradient(135deg,rgba(200,168,75,0.12),rgba(200,168,75,0.06))';e.currentTarget.style.boxShadow='none';}}>
          命 を 解 析 す る
        </button>

        {/* ログイン・会員登録 */}
        {!isLoggedIn && (
          <div style={{display:'flex',gap:'12px',width:'100%',justifyContent:'center',marginTop:'16px'}}>
            <button type="button" onClick={onLoginClick} style={{
              flex:1,maxWidth:'140px',padding:'10px',
              background:'transparent',border:'1px solid var(--gold-dim)',color:'var(--gold)',
              fontSize:'0.75rem',letterSpacing:'0.1em',fontFamily:'var(--serif-jp)',
              cursor:'pointer',transition:'all 0.3s ease',borderRadius:'2px'
            }}
              onMouseEnter={e=>{e.currentTarget.style.background='rgba(200,168,75,0.1)';}}
              onMouseLeave={e=>{e.currentTarget.style.background='transparent';}}>
              ログイン
            </button>
            <button type="button" onClick={onRegisterClick} style={{
              flex:1,maxWidth:'140px',padding:'10px',
              background:'rgba(200,168,75,0.1)',border:'1px solid var(--gold-dim)',color:'var(--gold)',
              fontSize:'0.75rem',letterSpacing:'0.1em',fontFamily:'var(--serif-jp)',
              cursor:'pointer',transition:'all 0.3s ease',borderRadius:'2px'
            }}
              onMouseEnter={e=>{e.currentTarget.style.background='rgba(200,168,75,0.15)';}}
              onMouseLeave={e=>{e.currentTarget.style.background='rgba(200,168,75,0.1)';}}>
              会員登録
            </button>
          </div>
        )}

      </form>
      <div style={{marginTop:'50px',opacity:0,animation:'fadeIn 1s ease 1.5s forwards',textAlign:'center'}}>
        <div style={{display:'flex',gap:'18px',justifyContent:'center'}}>
          {['一','二','三','四','五','六'].map((n,i)=>(
            <span key={n} style={{fontSize:'0.58rem',color:'var(--gold)',opacity:0.3+i*0.1,
              animation:`pulse-gold ${2+i*0.3}s ease-in-out ${i*0.2}s infinite`}}>{n}命</span>
          ))}
        </div>
      </div>

      {/* Footer */}
      <footer style={{
        position:'absolute',bottom:'24px',left:0,right:0,
        textAlign:'center',opacity:0,animation:'fadeIn 1s ease 1.8s forwards',
        padding:'0 20px',
      }}>
        <div style={{display:'flex',flexWrap:'wrap',alignItems:'center',justifyContent:'center',gap:'6px 14px'}}>
          <span style={{fontSize:'0.6rem',color:'var(--text-dim)',letterSpacing:'0.06em'}}>
            © Copyright — 株式会社リソース・シェアリング
          </span>
          <span style={{color:'var(--border)',fontSize:'0.6rem'}}>|</span>
          <a href="https://shared-todo.com/" target="_blank" rel="noopener noreferrer" style={{
            fontSize:'0.6rem',color:'var(--text-dim)',letterSpacing:'0.06em',
            textDecoration:'none',transition:'color 0.2s ease',
          }}
            onMouseEnter={e=>e.currentTarget.style.color='var(--gold)'}
            onMouseLeave={e=>e.currentTarget.style.color='var(--text-dim)'}>
            シェアードToDo
          </a>
          <span style={{color:'var(--border)',fontSize:'0.6rem'}}>|</span>
          <a href="https://investment-analysis.shared-todo.com/" target="_blank" rel="noopener noreferrer" style={{
            fontSize:'0.6rem',color:'var(--text-dim)',letterSpacing:'0.06em',
            textDecoration:'none',transition:'color 0.2s ease',
          }}
            onMouseEnter={e=>e.currentTarget.style.color='var(--gold)'}
            onMouseLeave={e=>e.currentTarget.style.color='var(--text-dim)'}>
            投資分析ダッシュボード
          </a>
        </div>
      </footer>
    </div>
  );
};

// ═══════════════════════════════════════════════════════
//  CELEBRITY DETAIL SCREEN
// ═══════════════════════════════════════════════════════
const CelebrityDetailScreen = ({ celebrity, onBack }) => {
  const [expandedEvent, setExpandedEvent] = React.useState(0);

  const getMonthPhase = (score) => {
    const val = score * 5;
    if (val >= 85) return { label: '勢いの月', desc: 'パワー全開。積極的に行動すれば大きな成果が期待できる月。新しいことに挑戦するのに最適です。' };
    if (val >= 70) return { label: '広がる月', desc: '活動や人間関係が広がる月。新しい出会いやチャンスが増え、視野も広がります。' };
    if (val >= 50) return { label: '整える月', desc: '現在の状況を整理し、基盤を強化する月。細部に注意を払い、質を高める工夫が効果的です。' };
    if (val >= 30) return { label: '見直す月', desc: '立ち止まって考える月。これまでのやり方を見直し、必要な調整を行うのに適しています。' };
    return { label: '休める月', desc: '心身を休める月。疲れを癒し、内省の時間を大切にしましょう。無理は避けて。' };
  };

  const getYearPhase = (score) => {
    const val = score * 5;
    if (val >= 85) return { label: '飛躍期', desc: '大きく動く・挑戦する年。新しいプロジェクトや目標達成に最適な時期。果敢に行動することで大きな成果が期待できます。' };
    if (val >= 70) return { label: '拡大期', desc: '活動や影響力を広げるのに良い時期。周囲との協力も進みやすく、成長が加速します。新しい出会いやチャンスに恵まれやすい。' };
    if (val >= 50) return { label: '安定期', desc: '基盤を固める時期。急激な変化よりも、現在の資産や関係を大切にしながら、着実に前に進むことが重要。質を高める工夫や改善に注力すると効果的。' };
    if (val >= 30) return { label: '調整期', desc: '見直し・整理・休息が必要な年。無理に進めるより、これまでの成果を整理し、次のステップへの準備を進めるべき時期。' };
    return { label: '準備期', desc: '無理に広げず、内側を整える年。基礎を強化し、自分自身と向き合う時間を大切に。次のステップへのエネルギー蓄積期。' };
  };

  const calcForEvent = (eventDateStr) => {
    const dt = new Date(eventDateStr);
    const y = dt.getFullYear();
    const m = dt.getMonth() + 1;
    const d = dt.getDate();
    const yp = getYearPillar(y);
    const mp = getMonthPillar(y, m);
    const dp = getDayPillar(y, m, d);
    const dominant = getDominantEl(y, m, d, null);
    const kyusei = calcKyusei(y, m);
    const zodiac = getZodiac(m, d);
    return { yp, mp, dp, dominant, kyusei, zodiac, y, m, d };
  };

  const getMatchReason = (evt, monthScore) => {
    const monthPhase = getMonthPhase(monthScore);
    const score100 = Math.round(monthScore * 5);
    const bucketMeta = getTransitionBucketMeta(evt);

    if (bucketMeta?.tone === 'exclude') {
      return bucketMeta.note;
    }

    if (bucketMeta?.tone === 'high') {
      return `補助判定: ${bucketMeta.label}（${bucketMeta.note}）`;
    }

    const polarity = evt?.polarity;
    const eventType = evt?.event_type;

    if (polarity === 'positive' && eventType === 'career') {
      if (monthScore >= 14) return `${monthPhase.label}（${score100}点）で始動期にマッチ：キャリアの新展開に適した時期`;
      return `点数が低く、キャリア開始には不向きな時期でした`;
    } else if (polarity === 'positive' && eventType === 'achievement') {
      if (monthScore >= 9) return `${monthPhase.label}（${score100}点）で成就期にマッチ：成果確定に適した時期`;
      return `点数が低く、成果確定には不向きな時期でした`;
    } else if (polarity === 'negative') {
      if (monthScore >= 5 && monthScore < 12) return `${monthPhase.label}（${score100}点）で調整期にマッチ：変化・調整に適した時期`;
      return `調整期（25-60点）から外れており、ネガティブなイベントの時期としては不向きでした`;
    }
    if (bucketMeta?.tone === 'medium') {
      return `補助判定: ${bucketMeta.label}（${bucketMeta.note}）`;
    }
    if (bucketMeta?.tone === 'low') {
      return `補助判定: ${bucketMeta.label}（${bucketMeta.note}）`;
    }
    return `マッチ理由を分析中...`;
  };

  return (
    <div style={{minHeight:'100vh',background:'var(--bg)',color:'var(--text)',paddingBottom:'60px'}}>
      <header style={{position:'sticky',top:0,zIndex:100,background:'rgba(5,5,8,0.95)',backdropFilter:'blur(8px)',borderBottom:'1px solid var(--border)',padding:'16px'}}>
        <div style={{maxWidth:'600px',margin:'0 auto',display:'flex',alignItems:'center',justifyContent:'space-between'}}>
          <button onClick={onBack} style={{background:'none',border:'none',color:'var(--gold)',cursor:'pointer',fontSize:'1.2rem',padding:'0'}}>
            ←
          </button>
          <h1 style={{flex:1,textAlign:'center',fontSize:'0.95rem',letterSpacing:'0.15em',margin:0}}>{celebrity.name}</h1>
          <div style={{width:'28px'}}/>
        </div>
      </header>

      <div style={{maxWidth:'600px',margin:'0 auto',padding:'24px 16px'}}>
        <div style={{background:'rgba(200,168,75,0.08)',padding:'16px',borderRadius:'6px',marginBottom:'24px'}}>
          <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:'12px',fontSize:'0.8rem'}}>
            <div>
              <div style={{color:'var(--text-dim)',marginBottom:'4px'}}>生年月日</div>
              <div style={{fontWeight:600,color:'var(--text-main)'}}>{celebrity.birth_date}</div>
            </div>
            <div>
              <div style={{color:'var(--text-dim)',marginBottom:'4px'}}>職業</div>
              <div style={{fontWeight:600,color:'var(--text-main)'}}>{celebrity.occupation_display || celebrity.occupation || '肩書き情報なし'}</div>
            </div>
          </div>
          <div style={{marginTop:'12px',paddingTop:'12px',borderTop:'1px solid rgba(200,168,75,0.2)',display:'grid',gridTemplateColumns:'1fr 1fr',gap:'12px',fontSize:'0.75rem'}}>
            <div>
              <div style={{color:'var(--text-dim)',marginBottom:'2px'}}>バックテスト精度</div>
              <div style={{color:'#c8a84b',fontWeight:600,fontSize:'1rem'}}>{Math.round(celebrity.accuracy)}%</div>
            </div>
            <div>
              <div style={{color:'var(--text-dim)',marginBottom:'2px'}}>マッチ実績</div>
              <div style={{color:'var(--text-main)',fontWeight:600,fontSize:'0.9rem'}}>{celebrity.matched_count}/{celebrity.total_tests}件</div>
            </div>
          </div>
        </div>

        <div>
          <p style={{fontSize:'0.75rem',letterSpacing:'0.1em',color:'var(--text-dim)',fontWeight:600,marginBottom:'12px',textTransform:'uppercase'}}>一致イベント解析</p>
          <div style={{display:'flex',flexDirection:'column',gap:'8px'}}>
            {celebrity.sample_events.map((evt, idx) => {
              const analysis = calcForEvent(evt.date);
              const isOpen = expandedEvent === idx;
              return (
                <div key={idx} style={{border:`1px solid ${isOpen ? 'var(--gold)' : 'var(--border)'}`,borderRadius:'6px',overflow:'hidden',background:'rgba(255,255,255,0.01)',transition:'all 0.2s ease'}}>
                  <button
                    onClick={() => setExpandedEvent(isOpen ? -1 : idx)}
                    style={{width:'100%',background:'none',border:'none',padding:'12px',textAlign:'left',cursor:'pointer',color:'inherit'}}
                    onMouseEnter={e => e.currentTarget.style.background='rgba(200,168,75,0.04)'}
                    onMouseLeave={e => e.currentTarget.style.background='none'}
                  >
                    <div style={{fontSize:'0.8rem',fontWeight:600,color:'var(--text-main)',marginBottom:'4px'}}>
                      {evt.date} — {evt.title}
                    </div>
                    {getTransitionBucketMeta(evt) && (
                      <div style={{display:'flex',flexWrap:'wrap',gap:'6px',marginBottom:'4px'}}>
                        <span style={{
                          fontSize:'0.6rem',
                          padding:'2px 6px',
                          border:'1px solid var(--border)',
                          borderRadius:'4px',
                          color:getTransitionBucketMeta(evt).tone === 'high' ? '#c8a84b' : 'var(--text-dim)',
                          background:'rgba(255,255,255,0.02)'
                        }}>
                          {getTransitionBucketMeta(evt).label}
                        </span>
                      </div>
                    )}
                    <div style={{fontSize:'0.7rem',color:'var(--text-dim)',display:'flex',gap:'12px'}}>
                      <span style={{color:'#5a9e8a',fontWeight:500}}>月: {getMonthPhase(evt.monthly_score).label}</span>
                      <span style={{color:'#5080a0',fontWeight:500}}>年: {getYearPhase(evt.yearly_score).label}</span>
                    </div>
                  </button>

                  {isOpen && (
                    <div style={{padding:'0 12px 12px',borderTop:'1px solid rgba(200,168,75,0.2)',fontSize:'0.7rem',animation:'fadeIn 0.2s ease'}}>
                      <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:'12px',marginBottom:'12px'}}>
                        <ReadingCard title="四柱推命" system="shichusuimei" index={0} accentColor="var(--gold)" defaultOpen={true}>
                          <div style={{fontSize:'0.7rem',lineHeight:1.8}}>
                            <div><strong>年柱:</strong> {analysis.yp.stem}{analysis.yp.branch} ({analysis.yp.el})</div>
                            <div><strong>月柱:</strong> {analysis.mp.stem}{analysis.mp.branch} ({analysis.mp.el})</div>
                            <div><strong>日柱:</strong> {analysis.dp.stem}{analysis.dp.branch} ({analysis.dp.el})</div>
                            <div style={{marginTop:'4px',color:'var(--gold)',fontWeight:600}}>主要五行: {analysis.dominant}</div>
                          </div>
                        </ReadingCard>
                        <ReadingCard title="九星気学" system="kyusei" index={1} accentColor="var(--gold)" defaultOpen={true}>
                          <div style={{fontSize:'0.7rem',lineHeight:1.8}}>
                            <div><strong>星:</strong> {KYUSEI_NAMES[analysis.kyusei - 1]}</div>
                            <div><strong>方位:</strong> {KYUSEI_DIRS[analysis.kyusei - 1]}</div>
                          </div>
                        </ReadingCard>
                      </div>
                      <ReadingCard title="イベント時の運勢" system="event" index={2} accentColor="var(--gold)" defaultOpen={true}>
                        <div style={{fontSize:'0.7rem',lineHeight:1.8,display:'flex',flexDirection:'column',gap:'12px'}}>
                          <div>
                            <div style={{color:'var(--text-dim)',marginBottom:'4px',fontWeight:600}}>月運</div>
                            <div style={{color:'#5a9e8a',fontWeight:600,fontSize:'0.9rem',marginBottom:'4px'}}>{getMonthPhase(evt.monthly_score).label}</div>
                            <div style={{color:'var(--text-dim)',fontSize:'0.65rem'}}>{getMonthPhase(evt.monthly_score).desc}</div>
                          </div>
                          <div>
                            <div style={{color:'var(--text-dim)',marginBottom:'4px',fontWeight:600}}>年運</div>
                            <div style={{color:'#5080a0',fontWeight:600,fontSize:'0.9rem',marginBottom:'4px'}}>{getYearPhase(evt.yearly_score).label}</div>
                            <div style={{color:'var(--text-dim)',fontSize:'0.65rem'}}>{getYearPhase(evt.yearly_score).desc}</div>
                          </div>
                        </div>
                      </ReadingCard>
                      <ReadingCard title="マッチ理由（的中根拠）" system="match" index={3} accentColor="var(--gold)" defaultOpen={true}>
                        <div style={{fontSize:'0.7rem',lineHeight:1.8,color:'var(--text-dim)'}}>
                          {getMatchReason(evt, evt.monthly_score)}
                        </div>
                      </ReadingCard>
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </div>

        <div style={{marginTop:'24px',padding:'16px',background:'rgba(200,168,75,0.05)',borderRadius:'4px',fontSize:'0.65rem',color:'var(--text-dim)',textAlign:'center'}}>
          著名人バックテストデータ: {celebrity.total_tests}件
        </div>
      </div>
    </div>
  );
};

// ═══════════════════════════════════════════════════════
//  RESULTS SCREEN
// ═══════════════════════════════════════════════════════
const ResultsScreen = ({ birthStr, timeStr, birthLatitude, birthLongitude, targetDateStr, onReset, tweaks, isLoggedIn, userName, onLoginClick, onRegisterClick, onLogoutClick, onMyPageClick, diagnosisId, typePatterns, userStatus = '有料会員' }) => {
  console.log('ResultsScreen userStatus:', userStatus);

  const locationCorrection = adjustDateTimeByLongitude(birthStr, timeStr, birthLongitude);

  const dt = new Date(birthStr);
  const y=dt.getFullYear(), m=dt.getMonth()+1, d=dt.getDate();
  const hourSource = timeStr;
  const hour = hourSource ? parseInt(String(hourSource).split(':')[0]) : null;

  // タイムマシン対応: targetDateStrがあればそちらを使う
  const targetDt = targetDateStr ? new Date(targetDateStr) : new Date();
  const ty=targetDt.getFullYear(), tm=targetDt.getMonth()+1, td=targetDt.getDate();
  const isTimeMachine = targetDateStr && targetDateStr !== (() => {
    const t=new Date(); return `${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,'0')}-${String(t.getDate()).padStart(2,'0')}`;
  })();

  // All calculations
  const yp = getYearPillar(y);
  const mp = getMonthPillar(y,m);
  const dp = getDayPillar(y,m,d);
  const hp = hour !== null ? getHourPillar(hour) : null;
  const domEl = getDominantEl(y,m,d,hour);
  const lifePath = calcLifePath(y,m,d);
  const lpData = LIFEPATH_DATA[lifePath] || LIFEPATH_DATA[1];
  const kyusei = calcKyusei(y,m);
  const zodiac = getZodiac(m,d);
  const bio = calcBio(y,m,d,ty,tm,td);
  const maya = calcMaya(y,m,d);
  const myType = determineType(lifePath, domEl, kyusei, zodiac);
  const typeInfo = SIX_TYPES[myType];
  const typePattern = typePatterns && typePatterns.types ? typePatterns.types.find(t => t.type_name === myType) : null;

  // 層1：OS診断（新仕様）
  const osResult = calcOSScores(lifePath, domEl, kyusei, zodiac, maya);
  const mainOSMeta = OS_META[osResult.mainOS];
  const subOSMeta = OS_META[osResult.subOS];

  // 層2・層3：運気診断
  const yearF = calcYearFortune(ty, y, m, d, domEl, lifePath, kyusei, zodiac, maya);
  const monthF = calcMonthFortune(ty, tm, y, m, d, domEl, lifePath, kyusei, zodiac, maya);
  const dayF = calcDayFortune(y, m, d, ty, tm, td, domEl, lifePath, kyusei, zodiac, maya);
  const compat = calcCompat(myType);
  const age = ty-y-(tm<m||(tm===m&&td<d)?1:0);
  const locationCorrectionLabel = locationCorrection
    ? `出生地補正メモ: ${locationCorrection.birthDate}${locationCorrection.birthTime ? ` ${locationCorrection.birthTime}` : ''} / ${locationCorrection.offsetMinutes >= 0 ? '+' : ''}${locationCorrection.offsetMinutes}分`
    : null;

  // OSスコアバーグラフコンポーネント
  const OSScoreBar = ({ osName, score, max=20 }) => (
    <div style={{marginBottom:'16px'}}>
      <div style={{display:'flex',justifyContent:'space-between',marginBottom:'6px'}}>
        <span style={{fontSize:'0.75rem',color:'var(--text)',fontWeight:500}}>{osName}</span>
        <span style={{fontSize:'0.7rem',color:'var(--text-dim)'}}>{Math.round(score)}/20</span>
      </div>
      <div style={{height:'6px',background:'rgba(255,255,255,0.08)',borderRadius:'3px',overflow:'hidden'}}>
        <div style={{height:'100%',width:`${Math.min(100,score/max*100)}%`,
          background:`linear-gradient(90deg, ${OS_META[osName]?.color||'#c8a84b'}, ${OS_META[osName]?.color||'#c8a84b'}dd)`,
          transition:'width 0.8s ease',boxShadow:`0 0 8px ${OS_META[osName]?.color||'#c8a84b'}60`}}/>
      </div>
    </div>
  );

  const accentColors = ['#c8a84b','#5a9e8a','#8080c0','#c06080','#5080a0','#a06030'];
  const fsScale = tweaks&&tweaks.fontSize==='large'?1.15:tweaks&&tweaks.fontSize==='small'?0.88:1;

  // Responsive detection
  const [isSmallScreen, setIsSmallScreen] = React.useState(window.innerWidth < 768);
  React.useEffect(() => {
    const handleResize = () => setIsSmallScreen(window.innerWidth < 768);
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  // Tabs for result sections
  const [activeTab, setActiveTab] = React.useState('综合');
  const tabs = ['综合','運勢','今日','相性'];
  const [recommendation, setRecommendation] = React.useState('');
  const [shareMessage, setShareMessage] = React.useState('');

  // 年運フェーズ（0-20スコア → 0-100に換算）
  const getYearPhase = (score) => {
    const val = score * 5;
    if (val >= 85) return { label: '飛躍期', desc: '大きく動く・挑戦する年。新しいプロジェクトや目標達成に最適な時期。果敢に行動することで大きな成果が期待できます。' };
    if (val >= 70) return { label: '拡大期', desc: '活動や影響力を広げるのに良い時期。周囲との協力も進みやすく、成長が加速します。新しい出会いやチャンスに恵まれやすい。' };
    if (val >= 50) return { label: '安定期', desc: '基盤を固める時期。急激な変化よりも、現在の資産や関係を大切にしながら、着実に前に進むことが重要。質を高める工夫や改善に注力すると効果的。' };
    if (val >= 30) return { label: '調整期', desc: '見直し・整理・休息が必要な年。無理に進めるより、これまでの成果を整理し、次のステップへの準備を進めるべき時期。' };
    return { label: '準備期', desc: '無理に広げず、内側を整える年。基礎を強化し、自分自身と向き合う時間を大切に。次のステップへのエネルギー蓄積期。' };
  };

  // 月運フェーズ（0-20スコア → 0-100に換算）
  const getMonthPhase = (score) => {
    const val = score * 5;
    if (val >= 85) return { label: '勢いの月', desc: 'パワー全開。積極的に行動すれば大きな成果が期待できる月。新しいことに挑戦するのに最適です。' };
    if (val >= 70) return { label: '広がる月', desc: '活動や人間関係が広がる月。新しい出会いやチャンスが増え、視野も広がります。' };
    if (val >= 50) return { label: '整える月', desc: '現在の状況を整理し、基盤を強化する月。細部に注意を払い、質を高める工夫が効果的です。' };
    if (val >= 30) return { label: '見直す月', desc: '立ち止まって考える月。これまでのやり方を見直し、必要な調整を行うのに適しています。' };
    return { label: '休める月', desc: '心身を休める月。疲れを癒し、内省の時間を大切にしましょう。無理は避けて。' };
  };

  // 今日のフェーズ（0-20スコア → 0-100に換算）
  const getDayPhase = (score) => {
    const val = score * 5;
    if (val >= 85) return { label: '攻める日', desc: 'エネルギー満タンの日。重要な決断や大きなチャレンジに挑戦するのに最適。積極的に行動を。' };
    if (val >= 70) return { label: '動く日', desc: '行動力が高い日。新しいことを始めたり、前に進めたい案件に取り組むのに向いています。' };
    if (val >= 50) return { label: '整える日', desc: '細かな調整や整理整頓に向いた日。細部に目を配り、質を高める作業が効果的。' };
    if (val >= 30) return { label: '慎重な日', desc: '慎重さが必要な日。大きな決断は避け、冷静に判断することが重要。見直しや準備作業に最適。' };
    return { label: '休む日', desc: '休息が必要な日。無理をせず、ゆっくりと過ごしましょう。心身のリセットが大切。' };
  };

  // キャリア指針（月運と年運から人生決断への適性を判定）
  const getCareerAdvice = (monthScore, yearScore) => {
    const combined = Math.round(monthScore * 0.6 + yearScore * 0.4);
    const signal = combined >= 15
      ? { label: '追い風', tone: 'high', note: '強く出た結果です。積極的に進めやすい時期です。' }
      : combined >= 11
        ? { label: 'やや出ています', tone: 'middle', note: '弱いシグナルはあります。強くは出ていないので参考扱いです。' }
        : combined >= 6
          ? { label: '見直し', tone: 'warn', note: '今は大きく動くより、見直して整える時期です。' }
          : { label: '保留', tone: 'none', note: 'この指標では強い判断を出していません。' };
    if (combined >= 15) return {
      level: '最高機',
      indicator: '🚀',
      headline: '人生の決断に最適なタイミング',
      signal,
      advice: '転職・昇進交渉・起業・重要プロジェクト開始などを前向きに検討しやすい月です。バックテストでは、こうしたテーマと重なりやすい傾向が見られました。大きな決断を進める際の参考として使ってください。',
      actions: ['転職・求人応募', '昇進交渉・キャリア相談', '起業・副業スタート', '重要なプロジェクト立案', '独立・新事業開始'],
      caution: null,
    };
    if (combined >= 11) return {
      level: '好機',
      indicator: '⬆️',
      headline: 'キャリアを展開させるのに向いた時期',
      signal,
      advice: '新スキル習得・ネットワーク拡大・新プロジェクト参加など、キャリアを段階的に広げやすい月です。動きを小さく始めると、その後の広がりにつながりやすい傾向があります。',
      actions: ['新スキル習得・資格取得', 'キャリア面談・相談', 'ネットワーキング活動', '新プロジェクト参加', '業務範囲の拡大提案'],
      caution: null,
    };
    if (combined >= 6) return {
      level: '調整',
      indicator: '→',
      headline: '現状を深め、次に備える時期',
      signal,
      advice: '大きく動くより、現在の職務を深めながら準備を整えたい時期です。見直しや改善を進めることで、次の動きにつながりやすくなります。',
      actions: ['現在のスキルをより深める', '業務の質を高める工夫', '長期キャリアプランの再確認', '人脈の整理・関係構築', '自分の市場価値の分析'],
      caution: '大きな決断は次の好機まで待つのが賢明',
    };
    return {
      level: '休養',
      indicator: '⏸',
      headline: '充電と内省の時期',
      signal,
      advice: '無理に動くより、休息や整理を優先したい時期です。今は強い判断を置かず、次の動きに向けて整えることを重視してください。',
      actions: ['自己分析・強み再発見', '学習・資格取得の準備', '体調管理・ストレス軽減', '人間関係の整理・修復', '将来のキャリアについて考える時間'],
      caution: '転職・起業・大きなキャリア決断は、今は急がない方がよい時期です',
    };
  };

  const shareResult = async (channel) => {
    if (!diagnosisId) {
      setShareMessage('共有URLを作るために、先に診断を保存してください');
      return;
    }
    if (!recommendation) {
      setShareMessage('先に当たり度を選択してください');
      return;
    }
    try {
      const res = await fetch('./api/diagnoses.php?action=create_share_link', {
        method: 'POST',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ diagnosis_id: diagnosisId, recommendation, channel }),
      });
      const data = await res.json();
      if (!data.success || !data.share_url) {
        setShareMessage(data.error || '共有URLの作成に失敗しました');
        return;
      }
      const url = data.share_url;
      if (channel === 'sns') {
        const text = encodeURIComponent('この診断、かなり面白かった！あなたもやってみて');
        window.open(`https://twitter.com/intent/tweet?text=${text}&url=${encodeURIComponent(url)}`, '_blank');
      } else if (channel === 'email') {
        location.href = `mailto:?subject=${encodeURIComponent('この診断をシェアします')}&body=${encodeURIComponent(url)}`;
      } else {
        await navigator.clipboard.writeText(url);
      }
      setShareMessage('共有URLを作成しました');
    } catch {
      setShareMessage('通信エラーで共有に失敗しました');
    }
  };

  return (
    <div style={{maxWidth:'740px',margin:'0 auto',padding:'40px 20px 100px',fontFamily:'var(--serif-jp)'}}>

      {/* ── Top nav: ブランド + ログイン/会員登録 ── */}
      <div style={{
        display:'flex',
        flexDirection:'column',
        gap:isSmallScreen?'20px':'16px',
        marginBottom:'32px',opacity:0,animation:'fadeIn 0.6s ease 0.1s forwards',
      }}>
        {/* ユーザー名 - ログイン時のみ表示 */}
        {isLoggedIn && (
          <div style={{
            display:'flex',
            flexDirection:'column',
            alignItems:'flex-end',
            gap:'8px',
          }}>
            {/* マイページ・ログアウト */}
            <div style={{
              display:'flex',
              gap:'8px',
            }}>
              <button onClick={onMyPageClick} style={{
                background:'none',border:'1px solid var(--border)',color:'var(--text-dim)',
                padding:'5px 12px',fontSize:'0.62rem',letterSpacing:'0.1em',
                fontFamily:'var(--serif-jp)',cursor:'pointer',borderRadius:'2px',transition:'all 0.2s ease',
              }}
                onMouseEnter={e=>{e.currentTarget.style.borderColor='var(--gold-dim)';e.currentTarget.style.color='var(--gold)';}}
                onMouseLeave={e=>{e.currentTarget.style.borderColor='var(--border)';e.currentTarget.style.color='var(--text-dim)';}}>
                マイページ
              </button>
              <button onClick={onLogoutClick} style={{
                background:'none',border:'1px solid var(--border)',color:'var(--text-dim)',
                padding:'5px 12px',fontSize:'0.62rem',letterSpacing:'0.1em',
                fontFamily:'var(--serif-jp)',cursor:'pointer',borderRadius:'2px',transition:'all 0.2s ease',
              }}
                onMouseEnter={e=>{e.currentTarget.style.borderColor='var(--gold-dim)';e.currentTarget.style.color='var(--gold)';}}
                onMouseLeave={e=>{e.currentTarget.style.borderColor='var(--border)';e.currentTarget.style.color='var(--text-dim)';}}>
                ログアウト
              </button>
            </div>

            {/* ユーザー名 */}
            <span style={{fontSize:'0.65rem',color:'var(--gold)',letterSpacing:'0.08em',whiteSpace:'nowrap'}}>
              {userName || 'ユーザー'} 様
            </span>
          </div>
        )}

        {/* Brand - センター寄せ */}
        <div style={{
          textAlign:'center',
          width:'100%',
        }}>
          <div style={{fontSize:'0.55rem',letterSpacing:'0.35em',color:'var(--gold)',fontFamily:'var(--serif-en)',textTransform:'uppercase',opacity:0.7,marginBottom:'3px'}}>Life Code Reading</div>
          <div style={{fontSize:'1.2rem',fontWeight:300,letterSpacing:'0.25em',
            background:'linear-gradient(180deg,rgba(232,204,128,0.95) 0%,rgba(200,168,75,0.7) 100%)',
            WebkitBackgroundClip:'text',WebkitTextFillColor:'transparent',backgroundClip:'text'}}>六命解析</div>
        </div>
      </div>

      {/* ── Header ── */}
      <div style={{textAlign:'center',marginBottom:'40px',opacity:0,animation:'fadeUp 0.7s ease 0.15s forwards'}}>
        <div style={{fontSize:'0.58rem',letterSpacing:'0.35em',color:'var(--text-dim)',marginBottom:'6px',fontFamily:'var(--serif-en)'}}>LIFE CODE READING</div>
        <div style={{fontSize:'0.85rem',color:'var(--gold)',letterSpacing:'0.2em',marginBottom:'3px'}}>
          {y}年 {m}月 {d}日{hour!==null?` ${hour}時台`:''}生まれ
        </div>
        <div style={{fontSize:'0.68rem',color:'var(--text-dim)',letterSpacing:'0.1em'}}>
          診断時の年齢 {age} 歳 · {ty}年{tm}月{td}日 解析
          {isTimeMachine && <span style={{marginLeft:'10px',color:'var(--gold)',fontSize:'0.65rem'}}>⏳ タイムマシン</span>}
        </div>
        <div style={{margin:'20px auto',width:'200px'}}><GoldDivider delay={0.3}/></div>
      </div>

      {/* ══════════════════════════════════════════
          1. 総合診断 - 6つの六命タイプ + 性格詳細
      ══════════════════════════════════════════ */}

      <SectionHeader num="01" label="総合診断" sub="あなたの六命タイプ" delay={0.5}/>

      {/* 六命タイプ表示 */}
      <div style={{
        border:'1px solid var(--border)',borderRadius:'2px',
        background:'rgba(255,255,255,0.015)',padding:'24px',
        marginBottom:'24px',
        opacity:0,animation:'reveal-card 0.7s ease 0.6s forwards',
      }}>
        {/* 上位3つのタイプ：主命・副命・内なる傾向（横並び） */}
        {(() => {
          const sorted = Object.entries(osResult.scores).sort((a,b)=>b[1]-a[1]).slice(0,3);
          const getTypeName = (osName) => OS_META[osName]?.jpName?.split(' ')[1] || '';
          const getTypeData = (osName) => typePatterns?.types?.find(t => t.type_name === getTypeName(osName));

          const main = { osName: sorted[0][0], label: '主命タイプ', score: sorted[0][1] };
          const sub = { osName: sorted[1][0], label: '副命タイプ', score: sorted[1][1] };
          const inner = { osName: sorted[2][0], label: '内なる傾向', score: sorted[2][1] };
          const mainData = getTypeData(main.osName);

          return (
            <>
              {/* 3つのタイプ（PCは横並び、スマホは縦） */}
              <div style={{display:'grid',gridTemplateColumns:isSmallScreen ? '1fr' : 'repeat(3, 1fr)',gap:'12px',marginBottom:'28px'}}>
                {[main, sub, inner].map((item, idx) => {
                  const typeData = getTypeData(item.osName);
                  return (
                    <div key={idx} style={{padding:'16px 14px',background:'rgba(255,255,255,0.05)',border:'1px solid rgba(200,168,75,0.15)',borderRadius:'2px',boxSizing:'border-box'}}>
                      <div style={{fontSize:'0.64rem',color:'var(--text-dim)',letterSpacing:'0.08em',marginBottom:'8px'}}>
                        {item.label}
                      </div>
                      <div style={{marginBottom:'10px'}}>
                        <div style={{fontSize:'1rem',color:'var(--text)',fontWeight:500}}>
                          {OS_META[item.osName]?.emoji} {OS_META[item.osName]?.jpName}
                        </div>
                      </div>
                      {typeData?.catchphrase && (
                        <div style={{fontSize:'0.7rem',color:'var(--text-dim)',lineHeight:1.5}}>
                          {typeData.catchphrase}
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>

              {/* 詳細分類と解説 */}
              <div style={{paddingTop:'20px',borderTop:'1px solid rgba(200,168,75,0.2)'}}>
                <div style={{fontSize:'0.7rem',color:'var(--text)',marginBottom:'12px',fontWeight:600}}>
                  🎯 詳細分類：{OS_META[main.osName]?.detailType}
                </div>
                <div style={{fontSize:'0.7rem',color:'var(--text)',lineHeight:1.8,marginBottom:'12px',background:'rgba(255,255,255,0.05)',padding:'12px',borderRadius:'2px'}}>
                  {main.osName === 'Drive' && '先行突破型とは、誰よりも早く行動し、新しい可能性を切り開くタイプです。物事を0から1に変える能力があります。'}
                  {main.osName === 'Care' && '信頼構築型とは、深い共感力で人間関係を築き、相手の心に寄り添うタイプです。人を育てることを通じて自分の価値を感じます。'}
                  {main.osName === 'Vision' && '世界観創造型とは、独自の視点で新しい世界を表現するタイプです。芸術、言語、音楽などを通じて、見えない何かを形にします。'}
                  {main.osName === 'Logic' && '本質解析型とは、表面的な情報を見抜き、物事の構造や真実を深く理解するタイプです。知的探求が生きがいです。'}
                  {main.osName === 'Quest' && '変化適応型とは、あらゆる環境に適応し、変化を楽しむタイプです。固定観念を打ち破り、新しいパラダイムをもたらします。'}
                  {main.osName === 'Balance' && '調和設計型とは、異なるものを統合し、全体のバランスを整えるタイプです。相反する要素を組み合わせ、新しい調和を生み出します。'}
                </div>
              </div>

                {/* 総合解釈 */}
                <div style={{paddingTop:'20px',borderTop:'1px solid rgba(200,168,75,0.2)',fontSize:'0.75rem',color:'var(--text)',lineHeight:1.9}}>
                  <p style={{margin:'0 0 12px 0'}}>
                    あなたは、{getTypeData(main.osName)?.catchphrase?.slice(0,-2)}、その場全体がうまく回るように自然と調整していくタイプです。
                  </p>
                  <p style={{margin:'12px 0'}}>
                    ただ優しいだけではなく、相手との距離感、言葉の温度、空気の変化を細かく感じ取る力があります。
                  </p>
                  <p style={{margin:'12px 0 0 0'}}>
                    さらに、{OS_META[inner.osName]?.jpName}の傾向もあるため、人を支えるだけでなく、自分の感性や考えを形にしたい気持ちも持っています。
                  </p>
                </div>
              </>
            );
          })()}
      </div>

      {/* 性格詳細セクション */}
      <div style={{
        border:'1px solid var(--border)',borderRadius:'2px',
        background:'rgba(255,255,255,0.015)',
        marginBottom:'40px',
        opacity:0,animation:'reveal-card 0.7s ease 0.7s forwards',
        overflow:'hidden',
      }}>
        {/* 詳細情報グリッド */}
        <div style={{padding:'24px'}}>
          {/* 性格の詳しい側面 */}
          <div style={{marginBottom:'28px'}}>
            <h3 style={{fontSize:'1.1rem',color:'var(--accent)',fontWeight:600,marginBottom:'16px',paddingBottom:'8px',borderBottom:'1px solid rgba(200,168,75,0.2)'}}>
              💎 あなたの特性
            </h3>
            <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fit, minmax(280px, 1fr))',gap:'12px'}}>
              <div style={{background:'rgba(200,168,75,0.08)',padding:'14px',borderRadius:'2px',border:'1px solid rgba(200,168,75,0.2)'}}>
                <div style={{fontSize:'0.75rem',color:'var(--accent)',fontWeight:600,letterSpacing:'0.1em',marginBottom:'6px'}}>✨ 強み</div>
                <div style={{fontSize:'0.7rem',color:'var(--text)',lineHeight:1.6}}>
                  {typePattern?.strength}
                </div>
              </div>
              <div style={{background:'rgba(200,168,75,0.08)',padding:'14px',borderRadius:'2px',border:'1px solid rgba(200,168,75,0.2)'}}>
                <div style={{fontSize:'0.75rem',color:'var(--accent)',fontWeight:600,letterSpacing:'0.1em',marginBottom:'6px'}}>💫 注意点</div>
                <div style={{fontSize:'0.7rem',color:'var(--text)',lineHeight:1.6}}>
                  {typePattern?.pitfall}
                </div>
              </div>
              <div style={{background:'rgba(200,168,75,0.08)',padding:'14px',borderRadius:'2px',border:'1px solid rgba(200,168,75,0.2)'}}>
                <div style={{fontSize:'0.75rem',color:'var(--accent)',fontWeight:600,letterSpacing:'0.1em',marginBottom:'6px'}}>👥 周囲からの見え方</div>
                <div style={{fontSize:'0.7rem',color:'var(--text)',lineHeight:1.6}}>
                  {typePattern?.seen_by_others}
                </div>
              </div>
              <div style={{background:'rgba(200,168,75,0.08)',padding:'14px',borderRadius:'2px',border:'1px solid rgba(200,168,75,0.2)'}}>
                <div style={{fontSize:'0.75rem',color:'var(--accent)',fontWeight:600,letterSpacing:'0.1em',marginBottom:'6px'}}>❤️ 本当の内面</div>
                <div style={{fontSize:'0.7rem',color:'var(--text)',lineHeight:1.6}}>
                  {typePattern?.true_inner}
                </div>
              </div>
            </div>
          </div>

          {/* その他のセクション */}
          <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fit, minmax(300px, 1fr))',gap:'28px'}}>
            <div>
              <h3 style={{fontSize:'1rem',color:'var(--accent)',fontWeight:600,marginBottom:'12px',paddingBottom:'8px',borderBottom:'1px solid rgba(200,168,75,0.2)'}}>
                🧭 人生テーマ
              </h3>
              <p style={{fontSize:'0.75rem',color:'var(--text)',lineHeight:1.8}}>
                {typePattern?.life_pattern}
              </p>
            </div>

            <div>
              <h3 style={{fontSize:'1rem',color:'var(--accent)',fontWeight:600,marginBottom:'12px',paddingBottom:'8px',borderBottom:'1px solid rgba(200,168,75,0.2)'}}>
                💕 恋愛・結婚
              </h3>
              <p style={{fontSize:'0.75rem',color:'var(--text)',lineHeight:1.8}}>
                {typePattern?.love || typeInfo?.love}
              </p>
            </div>

            <div>
              <h3 style={{fontSize:'1rem',color:'var(--accent)',fontWeight:600,marginBottom:'12px',paddingBottom:'8px',borderBottom:'1px solid rgba(200,168,75,0.2)'}}>
                💼 仕事・金運
              </h3>
              <p style={{fontSize:'0.75rem',color:'var(--text)',lineHeight:1.8}}>
                {typePattern?.work || typeInfo?.work}
              </p>
            </div>

            <div>
              <h3 style={{fontSize:'1rem',color:'var(--accent)',fontWeight:600,marginBottom:'12px',paddingBottom:'8px',borderBottom:'1px solid rgba(200,168,75,0.2)'}}>
                🤝 人間関係
              </h3>
              <p style={{fontSize:'0.75rem',color:'var(--text)',lineHeight:1.8}}>
                {typePattern?.human_relationship}
              </p>
            </div>
          </div>

        </div>
      </div>

      {locationCorrectionLabel && (
        <div style={{
          margin:'0 0 24px 0',
          padding:'12px 16px',
          border:'1px solid rgba(200,168,75,0.18)',
          borderRadius:'2px',
          background:'rgba(255,255,255,0.02)',
          color:'var(--text-dim)',
          fontSize:'0.72rem',
          lineHeight:1.7,
        }}>
          {locationCorrectionLabel}
          {locationCorrection.day_shift ? ` / 日付補正: ${locationCorrection.day_shift > 0 ? '+' : ''}${locationCorrection.day_shift}日` : ''}
        </div>
      )}

      {/* ══════════════════════════════════════════
          2. 運気診断 (年運・月運)
      ══════════════════════════════════════════ */}
      <SectionHeader num="02" label="運気診断" sub={`${ty}年 ${tm}月`} delay={0.9}/>
      <div style={{display:'grid',gridTemplateColumns:isSmallScreen ? '1fr' : '1fr 1fr',gap:'12px',marginBottom:'40px'}}>
        {/* 年運 */}
        <div style={{
          padding:'24px',border:'1px solid var(--border)',borderRadius:'2px',
          background:'rgba(255,255,255,0.015)',
          opacity:0,animation:'reveal-card 0.7s ease 1.0s forwards',
        }}>
          <div style={{fontSize:'0.58rem',letterSpacing:'0.2em',color:'var(--text)',marginBottom:'12px',textTransform:'uppercase'}}>{isTimeMachine ? 'その年' : '今年'}の年運</div>
          <div style={{display:'flex',alignItems:'baseline',gap:'10px',marginBottom:'16px'}}>
            <div style={{fontSize:'2.2rem',color:mainOSMeta.color,fontWeight:300}}>{yearF.emoji}</div>
            <div style={{fontSize:'0.95rem',color:'var(--text)',fontWeight:500}}>{yearF.phase}</div>
          </div>
          <div style={{fontSize:'0.65rem',color:'var(--text)',marginBottom:'8px',lineHeight:1.6}}>
            {yearF.desc}
          </div>
          <div style={{background:'rgba(255,255,255,0.05)',padding:'12px',borderRadius:'2px',marginBottom:'12px'}}>
            <div style={{fontSize:'0.8rem',color:'var(--text)',fontWeight:600,marginBottom:'6px'}}>{getYearPhase(yearF.score).label}</div>
            <div style={{fontSize:'0.7rem',color:'var(--text)',lineHeight:1.6}}>{getYearPhase(yearF.score).desc}</div>
          </div>
        </div>

        {/* 月運 */}
        <div style={{
          padding:'24px',border:'1px solid var(--border)',borderRadius:'2px',
          background:'rgba(255,255,255,0.015)',
          opacity:0,animation:'reveal-card 0.7s ease 1.1s forwards',
        }}>
          <div style={{fontSize:'0.58rem',letterSpacing:'0.2em',color:'var(--text)',marginBottom:'12px',textTransform:'uppercase'}}>{isTimeMachine ? 'その月' : '今月'}の月運</div>
          <div style={{display:'flex',alignItems:'baseline',gap:'10px',marginBottom:'16px'}}>
            <div style={{fontSize:'2.2rem',color:subOSMeta.color,fontWeight:300}}>{monthF.emoji}</div>
            <div style={{fontSize:'0.95rem',color:'var(--text)',fontWeight:500}}>{monthF.phase}</div>
          </div>
          <div style={{fontSize:'0.65rem',color:'var(--text)',marginBottom:'8px',lineHeight:1.6}}>
            {monthF.desc}
          </div>
          <div style={{background:'rgba(255,255,255,0.05)',padding:'12px',borderRadius:'2px',marginBottom:'12px'}}>
            <div style={{fontSize:'0.8rem',color:'var(--text)',fontWeight:600,marginBottom:'6px'}}>{getMonthPhase(monthF.score).label}</div>
            <div style={{fontSize:'0.7rem',color:'var(--text)',lineHeight:1.6}}>{getMonthPhase(monthF.score).desc}</div>
          </div>
        </div>
      </div>

      {/* ══════════════════════════════════════════
          3. キャリア指針
      ══════════════════════════════════════════ */}
      <SectionHeader num="03" label="キャリア指針" sub={isTimeMachine ? 'この月のキャリア判断（月運ベース）' : '今月のキャリア判断（月運ベース）'} delay={1.2}/>

      <div style={{marginBottom:'40px',opacity:0,animation:'reveal-card 0.7s ease 1.3s forwards'}}>
        {(() => {
          const ca = getCareerAdvice(monthF.score, yearF.score);
          const combined = Math.round(monthF.score * 0.6 + yearF.score * 0.4);
          const levelColor = combined >= 15 ? '#c8a84b' : combined >= 11 ? '#5a9e8a' : combined >= 6 ? 'var(--text-dim)' : '#8a8a9e';
          return (
            <div style={{padding:'24px',border:'1px solid var(--border)',borderRadius:'2px',background:'rgba(255,255,255,0.015)'}}>
              {/* ヘッダー: インジケーター + 月フェーズラベル + ヘッドライン */}
              <div style={{display:'flex',alignItems:'center',gap:'12px',marginBottom:'16px'}}>
                <div style={{fontSize:'1.8rem'}}>{ca.indicator}</div>
                <div>
                  <div style={{fontSize:'0.58rem',letterSpacing:'0.2em',color:levelColor,marginBottom:'2px'}}>{getMonthPhase(monthF.score).label}</div>
                  <div style={{fontSize:'0.95rem',color:'var(--text)',fontWeight:500}}>{ca.headline}</div>
                </div>
              </div>

              {ca.signal && (
                <div style={{
                  display:'inline-flex',
                  alignItems:'center',
                  gap:'8px',
                  marginBottom:'14px',
                  padding:'6px 10px',
                  border:`1px solid ${ca.signal.tone === 'high' ? 'var(--gold-dim)' : ca.signal.tone === 'warn' ? 'rgba(160,64,96,0.35)' : 'var(--border)'}`,
                  borderRadius:'4px',
                  background:'rgba(255,255,255,0.02)',
                  fontSize:'0.72rem',
                  color:'var(--text)',
                }}>
                  <span style={{color:ca.signal.tone === 'high' ? '#c8a84b' : ca.signal.tone === 'warn' ? '#d48aa0' : 'var(--text-dim)',fontWeight:600}}>
                    {ca.signal.label}
                  </span>
                  <span style={{color:'var(--text-dim)'}}>{ca.signal.note}</span>
                </div>
              )}

              {/* アドバイス本文 */}
              <div style={{fontSize:'0.7rem',color:'var(--text)',lineHeight:1.7,marginBottom:'16px'}}>
                {ca.advice}
              </div>

              {/* 推奨アクション */}
              <div style={{background:'rgba(255,255,255,0.05)',padding:'12px',borderRadius:'2px',marginBottom: ca.caution ? '12px' : '0'}}>
                <div style={{fontSize:'0.6rem',letterSpacing:'0.15em',color:'var(--text)',marginBottom:'8px'}}>推奨アクション</div>
                <div style={{display:'flex',flexWrap:'wrap',gap:'6px'}}>
                  {ca.actions.map((action, i) => (
                    <span key={i} style={{
                      fontSize:'0.65rem',padding:'3px 10px',
                      border:`1px solid ${levelColor}40`,borderRadius:'2px',
                      color:levelColor,background:`${levelColor}10`,
                    }}>{action}</span>
                  ))}
                </div>
              </div>

              {/* 注意事項（低スコア時のみ） */}
              {ca.caution && (
                <div style={{fontSize:'0.65rem',color:'var(--text-dim)',padding:'8px 12px',borderLeft:'2px solid rgba(255,255,255,0.1)',marginTop:'12px'}}>
                  ⚠️ {ca.caution}
                </div>
              )}

              {/* 出典 */}
              <div style={{fontSize:'0.55rem',color:'var(--text)',marginTop:'16px',marginBottom:'16px',lineHeight:1.6}}>
                ※ 運気分析（バックテストデータ）とは、有名人の生年月日とイベント発生日をもとに、六命解析の結果との関係を見た参考指標です。座標がある場合は経度補正を反映しますが、個別の結果を断定するものではありません。
              </div>

              {/* 向いている職業と解説 */}
              {(() => {
                const sorted = Object.entries(osResult.scores).sort((a,b)=>b[1]-a[1]).slice(0,2);
                const mainOSName = sorted[0]?.[0];
                const subOSName = sorted[1]?.[0];
                const careerInfo = mainOSName ? getOSCareerInfo(mainOSName, subOSName) : null;

                let careerReason = '';
                if (mainOSName === 'Drive') careerReason = '先行突破の推進力と';
                else if (mainOSName === 'Care') careerReason = '共感力と受容力の';
                else if (mainOSName === 'Vision') careerReason = 'クリエイティブな表現力と';
                else if (mainOSName === 'Logic') careerReason = '分析力と洞察力の';
                else if (mainOSName === 'Quest') careerReason = '適応力と自由さの';
                else if (mainOSName === 'Balance') careerReason = '調和とバランス感覚の';

                let subTypeDesc = '';
                if (subOSName === 'Drive') subTypeDesc = 'リーダーシップの側面';
                else if (subOSName === 'Care') subTypeDesc = '人を育てる側面';
                else if (subOSName === 'Vision') subTypeDesc = 'クリエイティブな側面';
                else if (subOSName === 'Logic') subTypeDesc = '分析的な側面';
                else if (subOSName === 'Quest') subTypeDesc = '自由さと適応力';
                else if (subOSName === 'Balance') subTypeDesc = 'バランス感覚';

                return careerInfo ? (
                  <div style={{marginTop:'16px',paddingTop:'16px',borderTop:'1px solid rgba(200,168,75,0.2)'}}>
                    <div style={{fontSize:'0.75rem',color:'var(--text)',marginBottom:'12px',fontWeight:600}}>
                      💼 向いている職業
                    </div>
                    <div style={{marginBottom:'16px'}}>
                      <div style={{display:'flex',alignItems:'baseline',gap:'12px',marginBottom:'12px'}}>
                        <div style={{fontSize:'0.9rem',color:'var(--accent)',fontWeight:600}}>
                          {careerInfo.career}
                        </div>
                        <div style={{fontSize:'0.8rem',color:'var(--gold)',fontWeight:600}}>
                          成功確率 {careerInfo.successRate}%
                        </div>
                      </div>
                      <div style={{fontSize:'0.7rem',color:'var(--text)',lineHeight:1.8,background:'rgba(255,255,255,0.05)',padding:'12px',borderRadius:'2px'}}>
                        主命タイプ「{OS_META[mainOSName]?.jpName}」の{careerReason}副命タイプ「{OS_META[subOSName]?.jpName}」の{subTypeDesc}が組み合わさったあなたには、この職業が向いています。バックテストデータから、この職種でのキャリア転換の成功確率は{careerInfo.successRate}%です。
                      </div>
                    </div>
                  </div>
                ) : null;
              })()}
            </div>
          );
        })()}
      </div>

      {/* ══════════════════════════════════════════
          4. 今日の占い
      ══════════════════════════════════════════ */}
      <SectionHeader num="04" label={isTimeMachine ? 'この日の占い' : '今日の占い'} sub={`${ty}年${tm}月${td}日`} delay={1.5}/>

      <div style={{marginBottom:'40px',opacity:0,animation:'reveal-card 0.7s ease 1.6s forwards'}}>
        {/* Day score - 2行レイアウト */}
        <div style={{
          display:'flex',flexDirection:'column',gap:'12px',
          padding:'24px',border:'1px solid var(--border)',borderRadius:'2px',
          background:'rgba(255,255,255,0.015)',marginBottom:'12px',
        }}>
          {/* 1行目：フェーズ説明 */}
          <div>
            <div style={{fontSize:'0.9rem',color:'var(--text)',fontWeight:600,marginBottom:'8px'}}>{getDayPhase(dayF.score).label}</div>
            <div style={{fontSize:'0.75rem',color:'var(--text)',lineHeight:1.6}}>{getDayPhase(dayF.score).desc}</div>
          </div>

          {/* 2行目：ラッキーアイテム */}
          <div>
            <div style={{display:'flex',gap:'16px',flexWrap:'wrap'}}>
              <div>
                <div style={{fontSize:'0.58rem',color:'var(--text-dim)',letterSpacing:'0.08em'}}>ラッキーカラー</div>
                <div style={{fontSize:'0.8rem',color:'var(--gold)',marginTop:'3px',fontWeight:500}}>{dayF.luckyItems.color}</div>
              </div>
              <div>
                <div style={{fontSize:'0.58rem',color:'var(--text-dim)',letterSpacing:'0.08em'}}>ラッキーナンバー</div>
                <div style={{fontSize:'0.8rem',color:'var(--gold)',marginTop:'3px',fontWeight:500}}>{dayF.luckyItems.number}</div>
              </div>
              <div>
                <div style={{fontSize:'0.58rem',color:'var(--text-dim)',letterSpacing:'0.08em'}}>吉方位</div>
                <div style={{fontSize:'0.8rem',color:'var(--gold)',marginTop:'3px',fontWeight:500}}>{dayF.luckyItems.direction}</div>
              </div>
              <div>
                <div style={{fontSize:'0.58rem',color:'var(--text-dim)',letterSpacing:'0.08em'}}>開運アイテム</div>
                <div style={{fontSize:'0.8rem',color:'var(--gold)',marginTop:'3px',fontWeight:500}}>{dayF.luckyItems.item}</div>
              </div>
            </div>
          </div>
        </div>

        {/* Action banner */}
        <div style={{
          background:'linear-gradient(135deg,rgba(200,168,75,0.08),rgba(200,168,75,0.03))',
          border:'1px solid rgba(200,168,75,0.25)',padding:'18px 22px',
          borderRadius:'2px',position:'relative',marginTop:'12px',
        }}>
          <div style={{position:'absolute',top:'-9px',left:'20px',background:'var(--void)',
            padding:'0 8px',fontSize:'0.58rem',letterSpacing:'0.2em',color:'var(--gold)',fontFamily:'var(--serif-jp)',letterSpacing:'0.15em'}}>
            開運アクション
          </div>
          <p style={{fontSize:`${0.82*fsScale}rem`,color:'var(--text)',lineHeight:2,letterSpacing:'0.08em'}}>
            ✦ {dayF.action}
          </p>
        </div>

        {/* Biorhythm mini */}
        <div style={{marginTop:'12px',padding:'18px 22px',border:'1px solid var(--border)',borderRadius:'2px',background:'rgba(255,255,255,0.015)'}}>
          <div style={{fontSize:'0.6rem',letterSpacing:'0.2em',color:'var(--text-dim)',marginBottom:'14px'}}>今日のバイオリズム</div>
          <BioChart data={dayF.bio} delay={1.4}/>
          <div style={{marginTop:'12px',fontSize:'0.7rem',color:'var(--text-dim)',lineHeight:1.8,borderTop:'1px solid rgba(200,168,75,0.1)',paddingTop:'12px'}}>
            <div style={{marginBottom:'10px'}}>
              <span style={{color:'var(--text)',fontWeight:500}}>📊 グラフの見方：</span>
            </div>
            <div style={{marginBottom:'8px',display:'flex',alignItems:'center',gap:'8px'}}>
              <span style={{width:'12px',height:'12px',background:'#c8a84b',borderRadius:'50%',flexShrink:0}}/>
              <span><span style={{color:'var(--text)',fontWeight:500}}>💪 身体リズム</span> — エネルギー、体力、活動性</span>
            </div>
            <div style={{marginBottom:'8px',display:'flex',alignItems:'center',gap:'8px'}}>
              <span style={{width:'12px',height:'12px',background:'#5a9e8a',borderRadius:'50%',flexShrink:0}}/>
              <span><span style={{color:'var(--text)',fontWeight:500}}>❤️ 感情リズム</span> — 気分、感性、対人関係</span>
            </div>
            <div style={{marginBottom:'10px',display:'flex',alignItems:'center',gap:'8px'}}>
              <span style={{width:'12px',height:'12px',background:'#8080c0',borderRadius:'50%',flexShrink:0}}/>
              <span><span style={{color:'var(--text)',fontWeight:500}}>🧠 知性リズム</span> — 集中力、判断力、学習力</span>
            </div>
            <div style={{marginTop:'10px',fontSize:'0.65rem',color:'var(--text-dim)',paddingTop:'8px',borderTop:'1px solid rgba(200,168,75,0.1)'}}>
              <div>↑ 上向き = 上昇期（好調）</div>
              <div>↓ 下向き = 下降期（調整が必要）</div>
            </div>
          </div>
        </div>
      </div>

      {/* ══════════════════════════════════════════
          会員登録のすすめ
      ══════════════════════════════════════════ */}
      {!isLoggedIn && (
      <div style={{
        background:'linear-gradient(135deg,rgba(200,168,75,0.15),rgba(200,168,75,0.05))',
        border:'1px solid rgba(200,168,75,0.3)',borderRadius:'2px',
        padding:'32px 24px',marginBottom:'48px',
        opacity:0,animation:'reveal-card 0.7s ease 2.5s forwards',
      }}>
        <div style={{fontSize:'0.65rem',letterSpacing:'0.2em',color:'var(--accent)',marginBottom:'8px',fontWeight:600}}>会員登録のすすめ</div>
        <div style={{fontSize:'1.1rem',color:'var(--text)',fontWeight:500,marginBottom:'24px',lineHeight:1.6}}>
          明日の運勢も受け取るために「会員登録」しませんか？
        </div>
        <div style={{display:'flex',flexDirection:'column',gap:'12px',marginBottom:'28px'}}>
          {[
            {icon:'⏳',text:'タイムマシン機能で「あの日の運勢」を振り返る'},
            {icon:'🔍',text:'過去の選択と運気の流れを見る'},
            {icon:'📅',text:'大事な日のライフコードを確認する'},
            {icon:'💫',text:'誕生日・転職日・告白日・別れた日・入社日を振り返る'},
          ].map((item, idx) => (
            <div key={idx} style={{fontSize:'0.75rem',color:'var(--text-dim)',lineHeight:1.6,display:'flex',alignItems:'flex-start',gap:'8px'}}>
              <span style={{fontSize:'1rem',flexShrink:0}}>{item.icon}</span>
              <span>{item.text}</span>
            </div>
          ))}
        </div>
        <button onClick={onRegisterClick} style={{
          background:'linear-gradient(135deg,rgba(200,168,75,0.3),rgba(200,168,75,0.15))',
          border:'1px solid var(--gold-dim)',color:'var(--gold)',
          padding:'14px 32px',borderRadius:'2px',cursor:'pointer',
          fontSize:'0.8rem',fontWeight:600,letterSpacing:'0.1em',
          transition:'all 0.3s ease',
        }}>
          無 料 で 会 員 登 録 す る
        </button>
      </div>
      )}

      {/* ══════════════════════════════════════════
          5. 六命解析について
      ══════════════════════════════════════════ */}
      <SectionHeader num="05" label="六命解析について" sub="6つの傾向タイプ" delay={1.5}/>

      <div style={{
        border:'1px solid var(--border)',borderRadius:'2px',
        background:'rgba(255,255,255,0.015)',padding:'24px',
        marginBottom:'48px',
        opacity:0,animation:'reveal-card 0.7s ease 2.6s forwards',
      }}>
        {/* 六命解析の説明 */}
        <div style={{fontSize:'0.7rem',color:'var(--text)',lineHeight:1.8,marginBottom:'24px'}}>
          <p style={{margin:'0 0 8px 0',color:'var(--text-dim)'}}>
            六命解析では、生年月日から6つの傾向スコアを算出し、<br/>
            最も強く出たものを「主命タイプ」、<br/>
            次に強く出たものを「副命タイプ」として読み解きます。
          </p>
          <p style={{margin:'12px 0',fontWeight:500,color:'var(--text)'}}>
            主命タイプは、あなたの中心にある性質。<br/>
            副命タイプは、あなたの中に混ざるもうひとつの傾向です。
          </p>
          <p style={{margin:'12px 0',fontWeight:500,color:'var(--text)'}}>
            内なる傾向は、ふだんは目立ちにくいけれど、<br/>
            状況によって表れやすい深い部分の性質です。
          </p>
          <p style={{margin:'12px 0 0 0',color:'var(--text-dim)',fontSize:'0.68rem'}}>
            この2つを組み合わせることで、<br/>
            単なる6分類ではなく、より立体的にあなたの本質を読み解きます。
          </p>
        </div>

        {/* 6つの六命タイプ説明 */}
        <div style={{paddingTop:'20px',borderTop:'1px solid rgba(200,168,75,0.2)'}}>
          <div style={{fontSize:'0.8rem',color:'var(--accent)',fontWeight:600,marginBottom:'14px'}}>6つの六命タイプとは</div>
          <div style={{display:'grid',gridTemplateColumns:isSmallScreen?'repeat(2, 1fr)':'repeat(3, 1fr)',gap:'10px'}}>
            {typePatterns?.types?.slice(0,6).map((type, idx) => (
              <div key={idx} style={{padding:'12px 10px',background:'rgba(255,255,255,0.04)',border:'1px solid rgba(200,168,75,0.1)',borderRadius:'2px',boxSizing:'border-box'}}>
                <div style={{fontSize:'0.8rem',color:'var(--text)',fontWeight:500,marginBottom:'5px'}}>
                  {type.type_emoji} {type.type_name}
                </div>
                <div style={{fontSize:'0.68rem',color:'var(--text-dim)',lineHeight:1.5}}>
                  {type.catchphrase}
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* ══════════════════════════════════════════
          6. 個別占い (6システム詳細) - 有料会員のみ表示
      ══════════════════════════════════════════ */}
      {userStatus === '有料会員' && (
        <>
          <SectionHeader num="07" label="個別占い詳細" sub="6システム解析" delay={1.9}/>

          <div style={{display:'flex',flexDirection:'column',gap:'10px',marginBottom:'48px'}}>

        {/* 四柱推命 */}
        <ReadingCard index="一" title={`${domEl}の命`} subtitle={`${yp.stem}${yp.branch} 年`}
          system="四柱推命" icon={yp.stem} delay={2.0} accentColor={accentColors[0]}>
          <div style={{display:'flex',flexDirection:'column',gap:'14px'}}>
            <p style={{fontSize:`${0.8*fsScale}rem`,color:'var(--text)',lineHeight:2,letterSpacing:'0.08em'}}>
              {ELEMENT_DATA[domEl]?.desc}あなたの本質的なエネルギーは<strong style={{color:'var(--gold)'}}>{domEl}気</strong>に支配されています。
            </p>
            <div style={{display:'grid',gridTemplateColumns:`repeat(${hp?'4':'3'},1fr)`,gap:'8px'}}>
              {[
                {label:'年柱',stem:yp.stem,branch:yp.branch,sub:yp.animal+'年'},
                {label:'月柱',stem:mp.stem,branch:mp.branch,sub:mp.el+'気'},
                {label:'日柱',stem:dp.stem,branch:dp.branch,sub:dp.el+'気'},
                ...(hp?[{label:'時柱',stem:'',branch:hp.branch,sub:hp.el+'気'}]:[]),
              ].map(({label,stem,branch,sub})=>(
                <div key={label} style={{textAlign:'center',padding:'10px 6px',border:'1px solid var(--border)',background:'rgba(255,255,255,0.02)',borderRadius:'2px'}}>
                  <div style={{fontSize:'0.58rem',color:'var(--text-dim)',letterSpacing:'0.1em',marginBottom:'6px'}}>{label}</div>
                  {stem&&<div style={{fontSize:'1.2rem',color:'var(--gold)',fontFamily:'var(--serif-jp)',lineHeight:1.2}}>{stem}</div>}
                  <div style={{fontSize:'1.1rem',color:'var(--text)',fontFamily:'var(--serif-jp)'}}>{branch}</div>
                  <div style={{fontSize:'0.6rem',color:'var(--text-dim)',marginTop:'4px'}}>{sub}</div>
                </div>
              ))}
            </div>
          </div>
        </ReadingCard>

        {/* 数秘術 */}
        <ReadingCard index="二" title={`ライフパス ${lifePath}`} subtitle={lpData.title}
          system="数秘術" icon={lifePath} delay={2.1} accentColor={accentColors[1]}>
          <div style={{display:'flex',gap:'18px',alignItems:'center'}}>
            <div style={{width:'68px',height:'68px',flexShrink:0,border:`1px solid ${accentColors[1]}40`,
              display:'flex',alignItems:'center',justifyContent:'center',
              background:`radial-gradient(circle,${accentColors[1]}10,transparent)`,borderRadius:'2px'}}>
              <span style={{fontSize:'2rem',color:accentColors[1],fontFamily:'var(--serif-en)',fontWeight:300}}>{lifePath}</span>
            </div>
            <div>
              <div style={{fontSize:'0.92rem',color:'var(--text)',letterSpacing:'0.1em',marginBottom:'6px'}}>{lpData.title}</div>
              <div style={{display:'flex',gap:'6px',flexWrap:'wrap'}}>
                {lpData.keywords.map(k=>(
                  <span key={k} style={{padding:'2px 8px',border:`1px solid ${accentColors[1]}30`,
                    background:`${accentColors[1]}10`,color:accentColors[1],fontSize:'0.68rem',letterSpacing:'0.1em',borderRadius:'1px'}}>{k}</span>
                ))}
              </div>
            </div>
          </div>
        </ReadingCard>

        {/* 九星気学 */}
        <ReadingCard index="三" title={KYUSEI_NAMES[kyusei-1]} subtitle={`恵方 ${KYUSEI_DIRS[kyusei-1]}`}
          system="九星気学" icon={`${kyusei}★`} delay={2.2} accentColor={accentColors[2]}>
          <div style={{display:'flex',gap:'18px',alignItems:'center'}}>
            <div style={{width:'68px',height:'68px',flexShrink:0,
              border:`1px solid ${KYUSEI_COLORS[kyusei-1]}50`,
              display:'flex',alignItems:'center',justifyContent:'center',
              background:`radial-gradient(circle,${KYUSEI_COLORS[kyusei-1]}15,transparent)`,
              borderRadius:'2px',flexDirection:'column'}}>
              <span style={{fontSize:'1.5rem',color:KYUSEI_COLORS[kyusei-1],fontFamily:'var(--serif-en)'}}>{kyusei}</span>
              <span style={{fontSize:'0.5rem',color:'var(--text-dim)'}}>★</span>
            </div>
            <p style={{fontSize:`${0.78*fsScale}rem`,color:'var(--text-dim)',lineHeight:1.9}}>
              {KYUSEI_NAMES[kyusei-1]}の気質。恵方<strong style={{color:KYUSEI_COLORS[kyusei-1]}}>{KYUSEI_DIRS[kyusei-1]}</strong>を意識することで運気が整います。
            </p>
          </div>
        </ReadingCard>

        {/* 12星座 */}
        <ReadingCard index="四" title={zodiac.name} subtitle={zodiac.symbol}
          system="12星座" icon={zodiac.symbol} delay={2.3} accentColor={accentColors[3]}>
          <p style={{fontSize:`${0.8*fsScale}rem`,color:'var(--text-dim)',lineHeight:2,letterSpacing:'0.08em'}}>
            <strong style={{color:accentColors[3]}}>{zodiac.name}</strong>に生まれたあなたは、星々の配置が織りなす独自の運命の糸を持ちます。
            本来の自分を信じて行動することで、隠れた才能が開花します。
          </p>
        </ReadingCard>

        {/* バイオリズム */}
        <ReadingCard index="五" title="生命波動" subtitle={`${bio.days.toLocaleString()} 日目`}
          system="バイオリズム" icon="波" delay={2.4} accentColor={accentColors[4]}>
          <div style={{display:'flex',flexDirection:'column',gap:'14px'}}>
            <BioChart data={bio} delay={2.5}/>
            <p style={{fontSize:`${0.76*fsScale}rem`,color:'var(--text-dim)',lineHeight:1.9,letterSpacing:'0.06em'}}>
              誕生から <strong style={{color:accentColors[4]}}>{bio.days.toLocaleString()}</strong> 日。
              肉体{bio.physical>0?'上昇':'調整'}期 · 感情{bio.emotional>0?'高揚':'内省'}期 · 知性{bio.intellectual>0?'活性':'蓄積'}期。
            </p>
          </div>
        </ReadingCard>

        {/* マヤ暦 */}
        <ReadingCard index="六" title={`${maya.tone}の${maya.kin}`} subtitle={`KIN ${maya.kinNum}`}
          system="マヤ暦" icon="☽" delay={2.5} accentColor={accentColors[5]}>
          <div style={{display:'flex',gap:'16px',alignItems:'center'}}>
            <div style={{width:'68px',height:'68px',flexShrink:0,
              border:`1px solid ${accentColors[5]}40`,
              display:'flex',alignItems:'center',justifyContent:'center',
              background:`radial-gradient(circle,${accentColors[5]}12,transparent)`,
              flexDirection:'column',gap:'2px',borderRadius:'2px'}}>
              <span style={{fontSize:'0.62rem',color:'var(--text-dim)'}}>KIN</span>
              <span style={{fontSize:'1.4rem',color:accentColors[5],fontFamily:'var(--serif-en)'}}>{maya.kinNum}</span>
              <span style={{fontSize:'0.5rem',color:'var(--text-dim)'}}>/260</span>
            </div>
            <p style={{fontSize:`${0.76*fsScale}rem`,color:'var(--text-dim)',lineHeight:1.9}}>
              マヤ暦KIN {maya.kinNum}「<strong style={{color:accentColors[5]}}>{maya.kin}</strong>」。
              {maya.tone}の波動があなたの使命を定めます。
            </p>
          </div>
        </ReadingCard>
      </div>
        </>
      )}

      {isLoggedIn && (
        <div style={{border:'1px solid var(--border)',padding:'16px',marginBottom:'26px',background:'rgba(255,255,255,0.02)'}}>
          <div style={{fontSize:'0.82rem',letterSpacing:'0.08em',color:'var(--gold)',marginBottom:'10px'}}>この診断、誰かに教えたいくらい当たっていましたか？</div>
          <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:'8px'}}>
            {[
              ['かなり当たっている','spark'],
              ['一部当たっている','partial'],
              ['まだわからない','unknown'],
              ['あまり当たっていない','low'],
            ].map(([label, value]) => (
              <button
                key={value}
                onClick={()=>setRecommendation(value)}
                style={{
                  padding:'12px 10px',
                  background: recommendation===value ? 'linear-gradient(135deg,rgba(200,168,75,0.28),rgba(200,168,75,0.12))' : 'rgba(255,255,255,0.03)',
                  border: recommendation===value ? '1px solid var(--gold-dim)' : '1px solid var(--border)',
                  color: recommendation===value ? 'var(--gold-light)' : 'var(--text-dim)',
                  cursor:'pointer',
                  letterSpacing:'0.06em',
                  fontSize:'0.72rem'
                }}
              >
                {label}
              </button>
            ))}
          </div>
          <div style={{marginTop:'10px',display:'flex',alignItems:'center',gap:'10px'}}>
            <button onClick={()=>shareResult('sns')} style={{background:'transparent',border:'1px solid var(--gold-dim)',color:'var(--gold)',padding:'8px 14px',cursor:'pointer'}}>SNSでシェア</button>
            <button onClick={()=>shareResult('email')} style={{background:'transparent',border:'1px solid var(--border)',color:'var(--text-dim)',padding:'8px 14px',cursor:'pointer'}}>メールで送る</button>
            <button onClick={()=>shareResult('copy')} style={{background:'transparent',border:'1px solid var(--border)',color:'var(--text-dim)',padding:'8px 14px',cursor:'pointer'}}>URLコピー</button>
          </div>
          <div style={{marginTop:'8px'}}>
            <span style={{fontSize:'0.68rem',color:'var(--text-dim)'}}>{shareMessage}</span>
          </div>
        </div>
      )}

      {/* Reset */}
      {!isLoggedIn && (
        <div style={{textAlign:'center',opacity:0,animation:'fadeIn 0.6s ease 2.8s forwards'}}>
          <button onClick={onReset} style={{
            background:'transparent',border:'1px solid var(--border)',color:'var(--text-dim)',
            padding:'10px 32px',fontSize:'0.72rem',letterSpacing:'0.2em',fontFamily:'var(--serif-jp)',
            cursor:'pointer',transition:'all 0.3s ease',borderRadius:'2px'}}
            onMouseEnter={e=>{e.currentTarget.style.borderColor='var(--gold-dim)';e.currentTarget.style.color='var(--gold)';}}
            onMouseLeave={e=>{e.currentTarget.style.borderColor='var(--border)';e.currentTarget.style.color='var(--text-dim)';}}>
            別の命を解析する
          </button>
        </div>
      )}
      {isLoggedIn && (
        <div style={{textAlign:'center',opacity:0,animation:'fadeIn 0.6s ease 2.8s forwards'}}>
          <button onClick={onReset} style={{
            background:'transparent',border:'1px solid var(--border)',color:'var(--text-dim)',
            padding:'10px 32px',fontSize:'0.72rem',letterSpacing:'0.2em',fontFamily:'var(--serif-jp)',
            cursor:'pointer',transition:'all 0.3s ease',borderRadius:'2px'}}
            onMouseEnter={e=>{e.currentTarget.style.borderColor='var(--gold-dim)';e.currentTarget.style.color='var(--gold)';}}
            onMouseLeave={e=>{e.currentTarget.style.borderColor='var(--border)';e.currentTarget.style.color='var(--text-dim)';}}>
            トップへ戻る
          </button>
        </div>
      )}

      {/* Footer */}
      <footer style={{
        marginTop:'60px',paddingTop:'24px',
        borderTop:'1px solid var(--border)',
        textAlign:'center',opacity:0,animation:'fadeIn 0.6s ease 3.0s forwards',
      }}>
        <div style={{display:'flex',flexWrap:'wrap',alignItems:'center',justifyContent:'center',gap:'8px 16px'}}>
          <span style={{fontSize:'0.62rem',color:'var(--text-dim)',letterSpacing:'0.08em'}}>
            © Copyright — 株式会社リソース・シェアリング
          </span>
          <span style={{color:'var(--border)',fontSize:'0.6rem'}}>|</span>
          <a href="https://shared-todo.com/" target="_blank" rel="noopener noreferrer" style={{
            fontSize:'0.62rem',color:'var(--text-dim)',letterSpacing:'0.08em',
            textDecoration:'none',transition:'color 0.2s ease',
          }}
            onMouseEnter={e=>e.currentTarget.style.color='var(--gold)'}
            onMouseLeave={e=>e.currentTarget.style.color='var(--text-dim)'}>
            シェアードToDo
          </a>
          <span style={{color:'var(--border)',fontSize:'0.6rem'}}>|</span>
          <a href="https://investment-analysis.shared-todo.com/" target="_blank" rel="noopener noreferrer" style={{
            fontSize:'0.62rem',color:'var(--text-dim)',letterSpacing:'0.08em',
            textDecoration:'none',transition:'color 0.2s ease',
          }}
            onMouseEnter={e=>e.currentTarget.style.color='var(--gold)'}
            onMouseLeave={e=>e.currentTarget.style.color='var(--text-dim)'}>
            投資分析ダッシュボード
          </a>
        </div>
      </footer>
    </div>
  );
};

// ═══ TWEAKS ═══
// ═══ LOGIN MODAL ═══
const LoginModal = ({ isOpen, onClose, initialTab='login', onLoginSuccess }) => {
  const [tab, setTab] = React.useState(initialTab);
  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [username, setUsername] = React.useState('');
  const [birthDate, setBirthDate] = React.useState('');
  const [birthTime, setBirthTime] = React.useState('');
  const [birthplace, setBirthplace] = React.useState('');
  const [gender, setGender] = React.useState('');
  const [region, setRegion] = React.useState('');
  const [occupationCategory, setOccupationCategory] = React.useState('');
  const [interestCategories, setInterestCategories] = React.useState([]);
  const [error, setError] = React.useState('');
  const [pendingVerificationEmail, setPendingVerificationEmail] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [resetEmail, setResetEmail] = React.useState('');
  const [resetStep, setResetStep] = React.useState('email');
  const [resetCode, setResetCode] = React.useState('');
  const [newPassword, setNewPassword] = React.useState('');

  React.useEffect(() => { if (isOpen) { setTab(initialTab); setError(''); } }, [isOpen, initialTab]);

  if (!isOpen) return null;

  const INTEREST_OPTIONS = [
    '恋愛','結婚・パートナー','仕事・キャリア','お金','人間関係','家族',
    '自己理解','将来・人生','健康・コンディション','学業・試験','引っ越し・環境変化','特にない','その他'
  ];
  const OCCUPATION_OPTIONS = [
    '会社員・公務員','経営者・役員','個人事業主・フリーランス','専門職','クリエイター',
    '販売・接客・サービス','営業・マーケティング','IT・エンジニア','教育・福祉','学生',
    '主婦・主夫','無職・休職中','その他','回答しない'
  ];

  const inputSt = {
    width:'100%', padding:'11px 14px', background:'rgba(255,255,255,0.04)',
    border:'1px solid rgba(200,168,75,0.25)', color:'var(--text)', fontSize:'0.85rem',
    fontFamily:'var(--serif-jp)', outline:'none', borderRadius:'2px', boxSizing:'border-box',
    colorScheme:'dark',
  };

  const handleLogin = async (e) => {
    e.preventDefault();
    if (!email || !password) { setError('メールアドレスとパスワードを入力してください'); return; }
    setLoading(true); setError('');
    setPendingVerificationEmail('');
    try {
      const fd = new FormData();
      fd.append('action','login'); fd.append('email',email); fd.append('password',password);
      const res = await fetch('./api/auth.php', { method:'POST', body:fd, credentials:'include' });
      const raw = await res.text();
      let data = null;
      try { data = JSON.parse(raw); } catch { data = { error: raw || `HTTP ${res.status}` }; }
      if (data.success) { onLoginSuccess(data.user); onClose(); }
      else {
        setError(data.error || 'ログインに失敗しました');
        if (data.code === 'EMAIL_NOT_VERIFIED') {
          setPendingVerificationEmail(data.email || email);
        }
      }
    } catch (err) { setError('接続エラー: ' + (err?.message || 'unknown')); }
    finally { setLoading(false); }
  };

  const handleRegister = async (e) => {
    e.preventDefault();
    if (!email || !password || !username || !birthDate) { setError('全ての必須項目を入力してください'); return; }
    if (interestCategories.length === 0) { setError('今知りたいテーマを1つ以上選択してください'); return; }
    if (password.length < 6) { setError('パスワードは6文字以上必要です'); return; }
    setLoading(true); setError('');
    setPendingVerificationEmail('');
    try {
      const fd = new FormData();
      fd.append('action','register'); fd.append('email',email); fd.append('password',password);
      fd.append('username',username); fd.append('birth_date',birthDate);
      fd.append('birth_time', birthTime);
      const parsedBirthplace = parseBirthLatLngValue(birthplace);
      fd.append('birth_latitude', parsedBirthplace.birthLatitude ?? '');
      fd.append('birth_longitude', parsedBirthplace.birthLongitude ?? '');
      fd.append('gender', gender);
      fd.append('region', region);
      fd.append('occupation_category', occupationCategory);
      fd.append('interest_categories', JSON.stringify(interestCategories));
      const res = await fetch('./api/auth.php', { method:'POST', body:fd, credentials:'include' });
      const raw = await res.text();
      let data = null;
      try { data = JSON.parse(raw); } catch { data = { error: raw || `HTTP ${res.status}` }; }
      if (data.success) {
        if (data.requires_email_verification) {
          const localHint = data.verification_url ? `（ローカル確認URL: ${data.verification_url}）` : '';
          setError(`登録完了: 認証メールを送信しました。メール内のURLを開いてからログインしてください。${localHint}`);
          setPendingVerificationEmail(email);
          setTab('login');
          setPassword('');
          return;
        }
        onLoginSuccess(data.user);
        onClose();
      } else {
        setError(data.error || '登録に失敗しました');
      }
    } catch (err) { setError('接続エラー: ' + (err?.message || 'unknown')); }
    finally { setLoading(false); }
  };

  const handleResendVerification = async () => {
    if (!pendingVerificationEmail) {
      setError('再送対象のメールアドレスがありません');
      return;
    }
    setLoading(true); setError('');
    try {
      const fd = new FormData();
      fd.append('action', 'resend_verification');
      fd.append('email', pendingVerificationEmail);
      const res = await fetch('./api/auth.php', { method: 'POST', body: fd, credentials: 'include' });
      const raw = await res.text();
      let data = null;
      try { data = JSON.parse(raw); } catch { data = { error: raw || `HTTP ${res.status}` }; }
      if (data.success) {
        const localHint = data.verification_url ? ` ローカル確認URL: ${data.verification_url}` : '';
        setError(`認証メールを再送しました。受信ボックスをご確認ください。${localHint}`);
      } else {
        setError(data.error || '認証メールの再送に失敗しました');
      }
    } catch (err) {
      setError('接続エラー: ' + (err?.message || 'unknown'));
    } finally {
      setLoading(false);
    }
  };

  const handleForgot = async (e) => {
    e.preventDefault();
    if (!resetEmail) { setError('メールアドレスを入力してください'); return; }
    setLoading(true); setError('');
    try {
      const fd = new FormData();
      fd.append('action','forgot_password'); fd.append('email',resetEmail);
      const res = await fetch('./api/auth.php', { method:'POST', body:fd, credentials:'include' });
      const data = await res.json();
      if (data.success) {
        if (data.reset_code) alert(`リセットコード: ${data.reset_code}`);
        setResetStep('code'); setError('');
      } else { setError(data.error || '送信に失敗しました'); }
    } catch { setError('送信に失敗しました'); }
    finally { setLoading(false); }
  };

  const handleReset = async (e) => {
    e.preventDefault();
    setLoading(true); setError('');
    try {
      const fd = new FormData();
      fd.append('action','reset_password'); fd.append('email',resetEmail);
      fd.append('reset_code',resetCode); fd.append('new_password',newPassword);
      const res = await fetch('./api/auth.php', { method:'POST', body:fd, credentials:'include' });
      const data = await res.json();
      if (data.success) { alert('パスワードをリセットしました。再度ログインしてください。'); setTab('login'); setResetStep('email'); }
      else { setError(data.error || 'リセットに失敗しました'); }
    } catch { setError('リセットに失敗しました'); }
    finally { setLoading(false); }
  };

  return (
    <div onClick={onClose} style={{
      position:'fixed',inset:0,background:'rgba(0,0,0,0.88)',zIndex:3000,
      display:'flex',alignItems:'center',justifyContent:'center',padding:'20px',
    }}>
      <div onClick={e=>e.stopPropagation()} style={{
        background:'linear-gradient(160deg,#0e0e1a,#080810)',
        border:'1px solid rgba(200,168,75,0.3)',
        borderRadius:'2px',padding:'36px 32px',width:'100%',maxWidth:'380px',
        boxShadow:'0 0 80px rgba(0,0,0,0.8), 0 0 40px rgba(200,168,75,0.05)',
        position:'relative',
      }}>
        {/* Close */}
        <button onClick={onClose} style={{
          position:'absolute',top:'14px',right:'16px',background:'none',border:'none',
          color:'var(--text-dim)',fontSize:'1rem',cursor:'pointer',
        }}>✕</button>

        {/* Header */}
        <div style={{textAlign:'center',marginBottom:'28px'}}>
          <div style={{fontSize:'0.55rem',letterSpacing:'0.3em',color:'var(--gold)',fontFamily:'var(--serif-en)',marginBottom:'8px',opacity:0.7}}>LIFE CODE</div>
          {tab !== 'forgot' && (
            <div style={{display:'flex',borderBottom:'1px solid var(--border)',marginBottom:'0'}}>
              {['login','register'].map(t=>(
                <button key={t} onClick={()=>{setTab(t);setError('');}} style={{
                  flex:1,padding:'10px',background:'none',border:'none',
                  borderBottom:`2px solid ${tab===t?'var(--gold)':'transparent'}`,
                  color:tab===t?'var(--gold)':'var(--text-dim)',
                  fontSize:'0.75rem',letterSpacing:'0.15em',cursor:'pointer',fontFamily:'var(--serif-jp)',
                  transition:'all 0.2s ease',
                }}>{t==='login'?'ログイン':'新規登録'}</button>
              ))}
            </div>
          )}
          {tab === 'forgot' && (
            <div style={{fontSize:'0.88rem',color:'var(--text)',letterSpacing:'0.1em'}}>パスワードをお忘れの方</div>
          )}
        </div>

        {/* Login form */}
        {tab === 'login' && (
          <form onSubmit={handleLogin} style={{display:'flex',flexDirection:'column',gap:'14px'}}>
            <input type="email" placeholder="メールアドレス" value={email} onChange={e=>setEmail(e.target.value)} style={inputSt} autoComplete="email"/>
            <input type="password" placeholder="パスワード" value={password} onChange={e=>setPassword(e.target.value)} style={inputSt} autoComplete="current-password"/>
            {error && <div style={{fontSize:'0.72rem',color:'#e06060',letterSpacing:'0.05em'}}>{error}</div>}
            {pendingVerificationEmail && (
              <button type="button" onClick={handleResendVerification} disabled={loading} style={{
                padding:'10px',background:'rgba(200,168,75,0.08)',border:'1px solid rgba(200,168,75,0.35)',
                color:'var(--gold-light)',fontSize:'0.72rem',letterSpacing:'0.1em',fontFamily:'var(--serif-jp)',
                cursor:'pointer',borderRadius:'2px'
              }}>
                認証メールを再送する
              </button>
            )}
            <button type="submit" disabled={loading} style={{
              padding:'13px',background:'linear-gradient(135deg,rgba(200,168,75,0.25),rgba(200,168,75,0.1))',
              border:'1px solid var(--gold-dim)',color:'var(--gold-light)',
              fontSize:'0.82rem',letterSpacing:'0.2em',fontFamily:'var(--serif-jp)',
              cursor:'pointer',borderRadius:'2px',transition:'all 0.3s ease',
            }}
              onMouseEnter={e=>{e.currentTarget.style.background='linear-gradient(135deg,rgba(200,168,75,0.38),rgba(200,168,75,0.18))';e.currentTarget.style.boxShadow='0 0 20px rgba(200,168,75,0.15)';}}
              onMouseLeave={e=>{e.currentTarget.style.background='linear-gradient(135deg,rgba(200,168,75,0.25),rgba(200,168,75,0.1))';e.currentTarget.style.boxShadow='none';}}>
              {loading ? '処理中...' : 'ログイン'}
            </button>
            <button type="button" onClick={()=>{setTab('forgot');setError('');}} style={{
              background:'none',border:'none',color:'var(--text-dim)',fontSize:'0.7rem',
              cursor:'pointer',letterSpacing:'0.08em',textDecoration:'underline',
            }}>パスワードをお忘れですか？</button>
          </form>
        )}

        {/* Register form */}
        {tab === 'register' && (
          <form onSubmit={handleRegister} style={{display:'flex',flexDirection:'column',gap:'12px'}}>
            <input type="text" placeholder="ユーザー名 *" value={username} onChange={e=>setUsername(e.target.value)} style={inputSt} autoComplete="username"/>
            <input type="email" placeholder="メールアドレス *" value={email} onChange={e=>setEmail(e.target.value)} style={inputSt} autoComplete="email"/>
            <div>
              <label style={{fontSize:'0.62rem',color:'var(--text-dim)',letterSpacing:'0.1em',display:'block',marginBottom:'6px'}}>生年月日 *</label>
              <input type="date" required value={birthDate} onChange={e=>setBirthDate(e.target.value)} style={inputSt} min="1900-01-01" max="2025-12-31" autoComplete="bday"/>
            </div>
            <div>
              <label style={{fontSize:'0.62rem',color:'var(--text-dim)',letterSpacing:'0.1em',display:'block',marginBottom:'6px'}}>生まれた時間（0〜23時・任意）</label>
              <input
                type="number"
                inputMode="numeric"
                min="0"
                max="23"
                step="1"
                value={birthTime}
                onChange={e=>setBirthTime(e.target.value)}
                style={inputSt}
                placeholder="12"
              />
            </div>
            <div>
              <label style={{fontSize:'0.62rem',color:'var(--text-dim)',letterSpacing:'0.1em',display:'block',marginBottom:'6px'}}>出生地（任意）</label>
              <input
                type="text"
                value={birthplace}
                onChange={e=>setBirthplace(e.target.value)}
                style={inputSt}
                placeholder="35.681236, 139.767125"
              />
            </div>
            <select value={gender} onChange={e=>setGender(e.target.value)} style={inputSt}>
              <option value="">性別（任意）</option>
              <option value="男性">男性</option>
              <option value="女性">女性</option>
              <option value="その他">その他</option>
              <option value="回答しない">回答しない</option>
            </select>
            <input type="text" placeholder="居住地域（任意）" value={region} onChange={e=>setRegion(e.target.value)} style={inputSt}/>
            <select value={occupationCategory} onChange={e=>setOccupationCategory(e.target.value)} style={inputSt}>
              <option value="">職業カテゴリ（任意）</option>
              {OCCUPATION_OPTIONS.map(opt => <option key={opt} value={opt}>{opt}</option>)}
            </select>
            <div style={{border:'1px solid rgba(200,168,75,0.2)',padding:'10px'}}>
              <div style={{fontSize:'0.62rem',color:'var(--text-dim)',letterSpacing:'0.1em',marginBottom:'8px'}}>今、特に知りたいテーマ *（複数選択可）</div>
              <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:'6px'}}>
                {INTEREST_OPTIONS.map(opt => (
                  <label key={opt} style={{fontSize:'0.72rem',color:'var(--text)',display:'flex',gap:'6px',alignItems:'center'}}>
                    <input
                      type="checkbox"
                      checked={interestCategories.includes(opt)}
                      onChange={(e)=>{
                        if (e.target.checked) setInterestCategories(prev => [...prev, opt]);
                        else setInterestCategories(prev => prev.filter(v => v !== opt));
                      }}
                    />
                    {opt}
                  </label>
                ))}
              </div>
            </div>
            <div>
              <label style={{fontSize:'0.62rem',color:'var(--text-dim)',letterSpacing:'0.1em',display:'block',marginBottom:'6px'}}>パスワード（6文字以上）*</label>
              <input type="password" required placeholder="パスワードを入力" value={password} onChange={e=>setPassword(e.target.value)} style={inputSt} autoComplete="new-password"/>
            </div>
            {error && <div style={{fontSize:'0.72rem',color:'#e06060',letterSpacing:'0.05em'}}>{error}</div>}
            <button type="submit" disabled={loading} style={{
              padding:'13px',background:'linear-gradient(135deg,rgba(200,168,75,0.25),rgba(200,168,75,0.1))',
              border:'1px solid var(--gold-dim)',color:'var(--gold-light)',
              fontSize:'0.82rem',letterSpacing:'0.2em',fontFamily:'var(--serif-jp)',
              cursor:'pointer',borderRadius:'2px',transition:'all 0.3s ease',
            }}
              onMouseEnter={e=>{e.currentTarget.style.background='linear-gradient(135deg,rgba(200,168,75,0.38),rgba(200,168,75,0.18))';e.currentTarget.style.boxShadow='0 0 20px rgba(200,168,75,0.15)';}}
              onMouseLeave={e=>{e.currentTarget.style.background='linear-gradient(135deg,rgba(200,168,75,0.25),rgba(200,168,75,0.1))';e.currentTarget.style.boxShadow='none';}}>
              {loading ? '処理中...' : '無 料 で 登 録 す る'}
            </button>
          </form>
        )}

        {/* Forgot password */}
        {tab === 'forgot' && resetStep === 'email' && (
          <form onSubmit={handleForgot} style={{display:'flex',flexDirection:'column',gap:'14px'}}>
            <p style={{fontSize:'0.75rem',color:'var(--text-dim)',lineHeight:1.8,letterSpacing:'0.06em'}}>登録済みのメールアドレスを入力してください。</p>
            <input type="email" placeholder="メールアドレス" value={resetEmail} onChange={e=>setResetEmail(e.target.value)} style={inputSt} autoComplete="email"/>
            {error && <div style={{fontSize:'0.72rem',color:'#e06060'}}>{error}</div>}
            <button type="submit" disabled={loading} style={{padding:'13px',background:'rgba(200,168,75,0.15)',border:'1px solid var(--gold-dim)',color:'var(--gold-light)',fontSize:'0.8rem',letterSpacing:'0.15em',cursor:'pointer',borderRadius:'2px',fontFamily:'var(--serif-jp)'}}>{loading?'送信中...':'送信する'}</button>
            <button type="button" onClick={()=>{setTab('login');setError('');}} style={{background:'none',border:'none',color:'var(--text-dim)',fontSize:'0.7rem',cursor:'pointer',letterSpacing:'0.08em'}}>← ログインに戻る</button>
          </form>
        )}
        {tab === 'forgot' && resetStep === 'code' && (
          <form onSubmit={handleReset} style={{display:'flex',flexDirection:'column',gap:'14px'}}>
            <input type="text" placeholder="リセットコード" value={resetCode} onChange={e=>setResetCode(e.target.value)} style={inputSt}/>
            <input type="password" placeholder="新しいパスワード" value={newPassword} onChange={e=>setNewPassword(e.target.value)} style={inputSt} autoComplete="new-password"/>
            {error && <div style={{fontSize:'0.72rem',color:'#e06060'}}>{error}</div>}
            <button type="submit" disabled={loading} style={{padding:'13px',background:'rgba(200,168,75,0.15)',border:'1px solid var(--gold-dim)',color:'var(--gold-light)',fontSize:'0.8rem',letterSpacing:'0.15em',cursor:'pointer',borderRadius:'2px',fontFamily:'var(--serif-jp)'}}>{loading?'処理中...':'パスワードを変更する'}</button>
          </form>
        )}
      </div>
    </div>
  );
};

const MyPageScreen = ({ user, onBack, onLogout, onUserUpdated, onUseEventDate }) => {
  const [username, setUsername] = React.useState(user?.username || '');
  const [email, setEmail] = React.useState(user?.email || '');
  const [birthDate, setBirthDate] = React.useState(user?.birth_date || '');
  const [birthTime, setBirthTime] = React.useState(formatHourInputValue(user?.birth_time || ''));
  const [birthplace, setBirthplace] = React.useState(formatBirthLatLngValue(user?.birth_latitude, user?.birth_longitude));
  const [profileMessage, setProfileMessage] = React.useState('');
  const [currentPassword, setCurrentPassword] = React.useState('');
  const [newPassword, setNewPassword] = React.useState('');
  const [passwordMessage, setPasswordMessage] = React.useState('');
  const [eventDate, setEventDate] = React.useState('');
  const [eventType, setEventType] = React.useState('');
  const [eventMemo, setEventMemo] = React.useState('');
  const [eventMessage, setEventMessage] = React.useState('');
  const [events, setEvents] = React.useState([]);
  const [editingEventId, setEditingEventId] = React.useState(null);
  const [editEventDate, setEditEventDate] = React.useState('');
  const [editEventType, setEditEventType] = React.useState('');
  const [editEventMemo, setEditEventMemo] = React.useState('');

  React.useEffect(() => {
    setUsername(user?.username || '');
    setEmail(user?.email || '');
    setBirthDate(user?.birth_date || '');
    setBirthTime(formatHourInputValue(user?.birth_time || ''));
    setBirthplace(formatBirthLatLngValue(user?.birth_latitude, user?.birth_longitude));
  }, [user]);

  const boxInput = {
    width:'100%',marginBottom:'8px',background:'rgba(255,255,255,0.04)',
    color:'var(--text)',border:'1px solid var(--border)',padding:'8px'
  };

  const loadEvents = async () => {
    try {
      const res = await fetch('./api/diagnoses.php?action=get_user_events&limit=50', { credentials:'include' });
      const data = await res.json();
      if (data.success && Array.isArray(data.events)) {
        setEvents(data.events);
      }
    } catch {}
  };

  React.useEffect(() => {
    loadEvents();
  }, []);

  const deleteEvent = async (eventId) => {
    try {
      const fd = new FormData();
      fd.append('event_id', String(eventId));
      const res = await fetch('./api/diagnoses.php?action=delete_user_event', {
        method:'POST',
        credentials:'include',
        body: fd,
      });
      const data = await res.json();
      if (data.success) {
        setEventMessage('イベントを削除しました');
        loadEvents();
      } else {
        setEventMessage(data.error || '削除に失敗しました');
      }
    } catch {
      setEventMessage('通信エラーで削除に失敗しました');
    }
  };

  const startEditEvent = (ev) => {
    setEditingEventId(ev.id);
    setEditEventDate(ev.event_date || '');
    setEditEventType(ev.event_type || '');
    setEditEventMemo(ev.memo || '');
  };

  const cancelEditEvent = () => {
    setEditingEventId(null);
    setEditEventDate('');
    setEditEventType('');
    setEditEventMemo('');
  };

  const updateEvent = async () => {
    if (!editingEventId || !editEventDate || !editEventType) {
      setEventMessage('更新には日付とイベント種別が必要です');
      return;
    }
    try {
      const fd = new FormData();
      fd.append('event_id', String(editingEventId));
      fd.append('event_date', editEventDate);
      fd.append('event_type', editEventType);
      fd.append('memo', editEventMemo);
      const res = await fetch('./api/diagnoses.php?action=update_user_event', {
        method:'POST',
        credentials:'include',
        body: fd,
      });
      const data = await res.json();
      if (data.success) {
        setEventMessage('イベントを更新しました');
        cancelEditEvent();
        loadEvents();
      } else {
        setEventMessage(data.error || '更新に失敗しました');
      }
    } catch {
      setEventMessage('通信エラーで更新に失敗しました');
    }
  };

  const updateProfile = async () => {
    if (!username || !email || !birthDate) {
      setProfileMessage('ユーザー名・メール・生年月日は必須です');
      return;
    }
    try {
      const fd = new FormData();
      fd.append('action', 'update_profile');
      fd.append('username', username);
      fd.append('email', email);
      fd.append('birth_date', birthDate);
      fd.append('birth_time', birthTime);
      const parsedBirthplace = parseBirthLatLngValue(birthplace);
      fd.append('birth_latitude', parsedBirthplace.birthLatitude ?? '');
      fd.append('birth_longitude', parsedBirthplace.birthLongitude ?? '');
      const res = await fetch('./api/auth.php', { method:'POST', credentials:'include', body: fd });
      const data = await res.json();
      if (data.success) {
        setProfileMessage('プロフィールを更新しました');
        onUserUpdated && onUserUpdated({ ...user, ...data.user });
      } else {
        setProfileMessage(data.error || '更新に失敗しました');
      }
    } catch {
      setProfileMessage('通信エラーで更新に失敗しました');
    }
  };

  const updatePassword = async () => {
    if (!currentPassword || !newPassword) {
      setPasswordMessage('現在のパスワードと新しいパスワードを入力してください');
      return;
    }
    try {
      const fd = new FormData();
      fd.append('action', 'change_password');
      fd.append('current_password', currentPassword);
      fd.append('new_password', newPassword);
      const res = await fetch('./api/auth.php', { method:'POST', credentials:'include', body: fd });
      const data = await res.json();
      if (data.success) {
        setPasswordMessage('パスワードを変更しました');
        setCurrentPassword('');
        setNewPassword('');
      } else {
        setPasswordMessage(data.error || '変更に失敗しました');
      }
    } catch {
      setPasswordMessage('通信エラーで変更に失敗しました');
    }
  };

  const saveEvent = async () => {
    if (!eventDate || !eventType) {
      setEventMessage('日付とイベント種別を入力してください');
      return;
    }
    try {
      const res = await fetch('./api/diagnoses.php?action=save_user_event', {
        method: 'POST',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ event_date: eventDate, event_type: eventType, memo: eventMemo }),
      });
      const data = await res.json();
      setEventMessage(data.success ? 'イベントを保存しました' : (data.error || '保存に失敗しました'));
      if (data.success) {
        setEventDate('');
        setEventType('');
        setEventMemo('');
        loadEvents();
      }
    } catch {
      setEventMessage('通信エラーで保存に失敗しました');
    }
  };

  return (
    <div style={{maxWidth:'740px',margin:'0 auto',padding:'40px 20px 100px',fontFamily:'var(--serif-jp)'}}>
      <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:'28px',flexWrap:'wrap',gap:'10px'}}>
        <button onClick={onBack} style={{
          background:'transparent',border:'1px solid var(--border)',color:'var(--text-dim)',
          padding:'6px 14px',fontSize:'0.65rem',letterSpacing:'0.12em',
          fontFamily:'var(--serif-jp)',cursor:'pointer',borderRadius:'2px'
        }}>戻る</button>
        <div style={{fontSize:'1.05rem',letterSpacing:'0.2em',color:'var(--gold)'}}>マイページ</div>
        <button onClick={onLogout} style={{
          background:'transparent',border:'1px solid var(--border)',color:'var(--text-dim)',
          padding:'6px 14px',fontSize:'0.65rem',letterSpacing:'0.12em',
          fontFamily:'var(--serif-jp)',cursor:'pointer',borderRadius:'2px'
        }}>ログアウト</button>
      </div>
      <div style={{border:'1px solid var(--border)',background:'rgba(255,255,255,0.015)',padding:'20px',lineHeight:2}}>
        <div style={{fontSize:'0.75rem',color:'var(--gold)',letterSpacing:'0.08em',marginBottom:'8px'}}>プロフィール編集</div>
        <label style={{fontSize:'0.68rem',color:'var(--text-dim)'}}>ユーザー名 *</label>
        <input type="text" value={username} onChange={e=>setUsername(e.target.value)} style={boxInput} />
        <label style={{fontSize:'0.68rem',color:'var(--text-dim)'}}>メールアドレス *</label>
        <input type="email" value={email} onChange={e=>setEmail(e.target.value)} style={boxInput} />
        <label style={{fontSize:'0.68rem',color:'var(--text-dim)'}}>生年月日 *</label>
        <input type="date" value={birthDate} onChange={e=>setBirthDate(e.target.value)} style={boxInput} />
        <label style={{fontSize:'0.68rem',color:'var(--text-dim)'}}>生まれた時間 <span style={{color:'var(--gold)',opacity:0.6}}>(0〜23時・任意)</span></label>
        <input
          type="number"
          inputMode="numeric"
          min="0"
          max="23"
          step="1"
          value={birthTime}
          onChange={e=>setBirthTime(e.target.value)}
          style={boxInput}
          placeholder="12"
        />
        <label style={{fontSize:'0.68rem',color:'var(--text-dim)'}}>出生地 <span style={{color:'var(--gold)',opacity:0.6}}>(任意)</span></label>
        <input
          type="text"
          value={birthplace}
          onChange={e=>setBirthplace(e.target.value)}
          style={boxInput}
          placeholder="35.681236, 139.767125"
        />
        <button onClick={updateProfile} style={{background:'transparent',border:'1px solid var(--gold-dim)',color:'var(--gold)',padding:'8px 14px',cursor:'pointer'}}>プロフィール保存</button>
        <span style={{marginLeft:'10px',fontSize:'0.68rem',color:'var(--text-dim)'}}>{profileMessage}</span>
      </div>
      <div style={{border:'1px solid var(--border)',background:'rgba(255,255,255,0.015)',padding:'20px',lineHeight:2,marginTop:'14px'}}>
        <div style={{fontSize:'0.75rem',color:'var(--gold)',letterSpacing:'0.08em',marginBottom:'8px'}}>パスワード変更</div>
        <label style={{fontSize:'0.68rem',color:'var(--text-dim)'}}>現在のパスワード *</label>
        <input type="password" value={currentPassword} onChange={e=>setCurrentPassword(e.target.value)} style={boxInput} />
        <label style={{fontSize:'0.68rem',color:'var(--text-dim)'}}>新しいパスワード *</label>
        <input type="password" value={newPassword} onChange={e=>setNewPassword(e.target.value)} style={boxInput} />
        <button onClick={updatePassword} style={{background:'transparent',border:'1px solid var(--gold-dim)',color:'var(--gold)',padding:'8px 14px',cursor:'pointer'}}>パスワード保存</button>
        <span style={{marginLeft:'10px',fontSize:'0.68rem',color:'var(--text-dim)'}}>{passwordMessage}</span>
      </div>
      <div style={{border:'1px solid var(--border)',background:'rgba(255,255,255,0.015)',padding:'20px',lineHeight:2,marginTop:'14px'}}>
        <div style={{fontSize:'0.75rem',color:'var(--gold)',letterSpacing:'0.08em',marginBottom:'8px'}}>タイムマシン用イベント登録</div>
        <input type="date" value={eventDate} onChange={e=>setEventDate(e.target.value)} style={boxInput} />
        <input type="text" placeholder="イベント種別（例: 転職日）" value={eventType} onChange={e=>setEventType(e.target.value)} style={boxInput} />
        <textarea placeholder="メモ（任意）" value={eventMemo} onChange={e=>setEventMemo(e.target.value)} style={{...boxInput,minHeight:'65px'}} />
        <button onClick={saveEvent} style={{background:'transparent',border:'1px solid var(--gold-dim)',color:'var(--gold)',padding:'8px 14px',cursor:'pointer'}}>イベント保存</button>
        <span style={{marginLeft:'10px',fontSize:'0.68rem',color:'var(--text-dim)'}}>{eventMessage}</span>
      </div>
      <div style={{border:'1px solid var(--border)',background:'rgba(255,255,255,0.015)',padding:'20px',lineHeight:2,marginTop:'14px'}}>
        <div style={{fontSize:'0.75rem',color:'var(--gold)',letterSpacing:'0.08em',marginBottom:'8px'}}>保存済みイベント</div>
        {events.length === 0 && <div style={{fontSize:'0.72rem',color:'var(--text-dim)'}}>まだイベントはありません</div>}
        {events.map(ev => (
          <div key={ev.id} style={{borderTop:'1px solid var(--border)',padding:'10px 0'}}>
            {editingEventId === ev.id ? (
              <>
                <input type="date" value={editEventDate} onChange={e=>setEditEventDate(e.target.value)} style={boxInput} />
                <input type="text" value={editEventType} onChange={e=>setEditEventType(e.target.value)} style={boxInput} />
                <textarea value={editEventMemo} onChange={e=>setEditEventMemo(e.target.value)} style={{...boxInput,minHeight:'60px'}} />
                <div style={{display:'flex',gap:'8px',marginTop:'6px'}}>
                  <button onClick={updateEvent} style={{background:'transparent',border:'1px solid var(--gold-dim)',color:'var(--gold)',padding:'4px 10px',cursor:'pointer',fontSize:'0.66rem'}}>更新</button>
                  <button onClick={cancelEditEvent} style={{background:'transparent',border:'1px solid var(--border)',color:'var(--text-dim)',padding:'4px 10px',cursor:'pointer',fontSize:'0.66rem'}}>キャンセル</button>
                </div>
              </>
            ) : (
              <>
                <div style={{fontSize:'0.72rem',color:'var(--text)'}}>{ev.event_date} / {ev.event_type}</div>
                {ev.memo && <div style={{fontSize:'0.68rem',color:'var(--text-dim)'}}>{ev.memo}</div>}
                <div style={{display:'flex',gap:'8px',marginTop:'6px'}}>
                  <button
                    onClick={()=>onUseEventDate && onUseEventDate(ev.event_date)}
                    style={{background:'transparent',border:'1px solid var(--gold-dim)',color:'var(--gold)',padding:'4px 10px',cursor:'pointer',fontSize:'0.66rem'}}
                  >
                    この日で診断
                  </button>
                  <button
                    onClick={()=>startEditEvent(ev)}
                    style={{background:'transparent',border:'1px solid var(--border)',color:'var(--text-dim)',padding:'4px 10px',cursor:'pointer',fontSize:'0.66rem'}}
                  >
                    編集
                  </button>
                  <button
                    onClick={()=>deleteEvent(ev.id)}
                    style={{background:'transparent',border:'1px solid rgba(180,80,80,0.5)',color:'#d98c8c',padding:'4px 10px',cursor:'pointer',fontSize:'0.66rem'}}
                  >
                    削除
                  </button>
                </div>
              </>
            )}
          </div>
        ))}
      </div>
    </div>
  );
};

const AppTweaks = ({ tweaks, setTweak }) => {
  if (!tweaks) return null;
  return (
    <TweaksPanel title="Tweaks">
      <TweakSection label="表示設定">
        <TweakRadio id="fontSize" label="文字サイズ"
          options={[{value:'small',label:'小'},{value:'normal',label:'標準'},{value:'large',label:'大'}]}
          value={tweaks.fontSize} onChange={v=>setTweak('fontSize',v)}/>
        <TweakToggle id="showOrbs" label="装飾リング"
          value={tweaks.showOrbs} onChange={v=>setTweak('showOrbs',v)}/>
      </TweakSection>
      <TweakSection label="カラーテーマ">
        <TweakRadio id="theme" label="アクセント"
          options={[{value:'gold',label:'金'},{value:'jade',label:'翠'},{value:'silver',label:'銀'}]}
          value={tweaks.theme} onChange={v=>setTweak('theme',v)}/>
      </TweakSection>
    </TweaksPanel>
  );
};

// ═══ MAIN APP ═══
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "fontSize": "normal",
  "showOrbs": true,
  "theme": "gold"
}/*EDITMODE-END*/;

const App = () => {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [screen, setScreen] = React.useState('hero');
  const [birthStr, setBirthStr] = React.useState('');
  const [timeStr, setTimeStr] = React.useState(null);
  const [birthLatitudeStr, setBirthLatitudeStr] = React.useState(null);
  const [birthLongitudeStr, setBirthLongitudeStr] = React.useState(null);
  const [targetDateStr, setTargetDateStr] = React.useState(null);
  const [user, setUser] = React.useState(null);
  const [modal, setModal] = React.useState({ open: false, tab: 'login' });
  const [lastDiagnosisId, setLastDiagnosisId] = React.useState(null);
  const [typePatterns, setTypePatterns] = React.useState(null);
  const [selectedCelebrity, setSelectedCelebrity] = React.useState(null);
  const isLoggedIn = !!user;

  // ユーザー情報（ログイン時は実際のデータ、未ログイン時は空）
  const userBirth = user?.birth_date || '';
  const userTime  = user?.birth_time || '';
  const userBirthLatitude = user?.birth_latitude ?? '';
  const userBirthLongitude = user?.birth_longitude ?? '';

  if (!tweaks) return null;

  // 起動時に type_patterns を読み込み
  React.useEffect(() => {
    fetch('./config/type_patterns.json', {
      cache: 'no-store',
    })
      .then(r => r.json())
      .then(data => {
        if (data && data.types) {
          setTypePatterns(data);
        }
      })
      .catch(() => {});
  }, []);

  // 起動時にセッション確認
  React.useEffect(() => {
    fetch(`./api/auth.php?action=me&_ts=${Date.now()}`, {
      credentials: 'include',
      cache: 'no-store',
    })
      .then(r => r.json())
      .then(data => {
        if (data.isLoggedIn && data.user) {
          setUser(data.user);
        } else {
          setUser(null);
        }
      })
      .catch(() => {});
  }, []);

  React.useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const shareToken = params.get('share');
    if (!shareToken) return;
    fetch(`./api/diagnoses.php?action=get_shared_diagnosis&token=${encodeURIComponent(shareToken)}`, {
      credentials: 'include',
      cache: 'no-store',
    })
      .then(r => r.json())
      .then(data => {
        if (!data.success || !data.diagnosis) return;
        const d = data.diagnosis;
        const dr = d.diagnosis_result || {};
        setBirthStr(d.birthday || '');
        setTimeStr(d.birth_time || null);
        setBirthLatitudeStr(d.birth_latitude ?? dr.birth_latitude ?? null);
        setBirthLongitudeStr(d.birth_longitude ?? dr.birth_longitude ?? null);
        setTargetDateStr(d.target_date || null);
        setScreen('results');
      })
      .catch(() => {});
  }, []);

  React.useEffect(()=>{
    const themes = {
      gold:   {main:'#c8a84b',light:'#e8cc80',dim:'rgba(200,168,75,0.4)'},
      jade:   {main:'#5a9e8a',light:'#7dc4b0',dim:'rgba(90,158,138,0.4)'},
      silver: {main:'#9090b8',light:'#b8b8d0',dim:'rgba(144,144,184,0.4)'},
    };
    const t = themes[tweaks.theme]||themes.gold;
    document.documentElement.style.setProperty('--gold',t.main);
    document.documentElement.style.setProperty('--gold-light',t.light);
    document.documentElement.style.setProperty('--gold-dim',t.dim);
  },[tweaks.theme]);

  const handleLoginSuccess = (userData) => {
    setUser(userData);
  };

  const handleLogout = async () => {
    await fetch('./api/auth.php', {
      method: 'POST',
      body: (() => { const fd = new FormData(); fd.append('action','logout'); return fd; })()
    });
    setUser(null);
    setScreen('hero');
  };

  const openLogin    = () => setModal({ open: true, tab: 'login' });
  const openRegister = () => setModal({ open: true, tab: 'register' });
  const closeModal   = () => setModal({ open: false, tab: modal.tab });

  const handleSubmit = (birth, time, targetDate, birthplace = {}) => {
    if (!birth) {
      return;
    }
    setBirthStr(birth);
    setTimeStr(time);
    setBirthLatitudeStr(birthplace.birthLatitude || null);
    setBirthLongitudeStr(birthplace.birthLongitude || null);
    setTargetDateStr(targetDate || null);
    fetch('./api/diagnoses.php?action=save_diagnosis', {
      method: 'POST',
      credentials: 'include',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        birthday: birth,
        birth_time: time !== '' && time !== null && typeof time !== 'undefined'
          ? formatBirthTimeForStorage(time)
          : null,
        diagnosis_result: {
          target_date: targetDate || null,
          source: 'local_ui',
          birth_latitude: birthplace.birthLatitude || null,
          birth_longitude: birthplace.birthLongitude || null,
        },
      }),
    }).then(r => r.json()).then(data => {
      if (data && data.success && data.diagnosis_id) {
        setLastDiagnosisId(data.diagnosis_id);
      }
    }).catch(() => {});
    setScreen('loading');
  };
  const handleLoaded = () => setScreen('results');
  const handleReset  = () => { setScreen('hero'); setBirthStr(''); setTimeStr(null); setBirthLatitudeStr(null); setBirthLongitudeStr(null); setTargetDateStr(null); };
  const handleMyPage = () => setScreen('mypage');
  const handleMyPageBack = () => setScreen(birthStr ? 'results' : 'hero');
  const handleUseEventDate = (eventDate) => {
    setTargetDateStr(eventDate);
    setScreen('hero');
  };

  return (
    <>
      {screen==='hero'    && <HeroScreen onSubmit={handleSubmit} isLoggedIn={isLoggedIn} userBirth={userBirth} userTime={userTime} userBirthLatitude={userBirthLatitude} userBirthLongitude={userBirthLongitude} userName={user?.username} onLoginClick={openLogin} onRegisterClick={openRegister} onLogoutClick={handleLogout} onMyPageClick={handleMyPage} preselectedTargetDate={targetDateStr} onSelectCelebrity={(celeb) => {setSelectedCelebrity(celeb); setScreen('celebrity_detail');}}/>}
      {screen==='loading' && <LoadingOracle onComplete={handleLoaded}/>}
      {screen==='results' && <ResultsScreen birthStr={birthStr} timeStr={timeStr} birthLatitude={birthLatitudeStr} birthLongitude={birthLongitudeStr} targetDateStr={targetDateStr} onReset={handleReset} tweaks={tweaks} isLoggedIn={isLoggedIn} userName={user?.username} onLoginClick={openLogin} onRegisterClick={openRegister} onLogoutClick={handleLogout} onMyPageClick={handleMyPage} diagnosisId={lastDiagnosisId} typePatterns={typePatterns} userStatus={user?.membership_status || '未登録'}/>}
      {screen==='celebrity_detail' && selectedCelebrity && <CelebrityDetailScreen celebrity={selectedCelebrity} onBack={() => setScreen('hero')}/>}
      {screen==='mypage'  && <MyPageScreen user={user} onBack={handleMyPageBack} onLogout={handleLogout} onUserUpdated={setUser} onUseEventDate={handleUseEventDate}/>}
      <LoginModal isOpen={modal.open} onClose={closeModal} initialTab={modal.tab} onLoginSuccess={handleLoginSuccess}/>
      <AppTweaks tweaks={tweaks} setTweak={setTweak}/>
    </>
  );
};

ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
