メインコンテンツへスキップ
見出し画像

結果分析コード

    コメントありがとうございます

    それでは、結果分析コードです。
    ホーム画面に入れてみて下さい。
    ※本番は5つまでコードを実装できます



    以下が結果分析コード
    使いやすいようにアレンジしてくださいね

    コードの右側を押すと□ボタンが現れコピーできます

    <!DOCTYPE html>
    <html lang="ja">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Analytics Dash PRO - 競馬レース結果分析</title>
        <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
        <style>
            body { margin: 0; padding: 0; font-family: "Helvetica Neue", Arial, "Hiragino Kaku Gothic ProN", "Hiragino Sans", Meiryo, sans-serif; background-color: #f0f4f8; color: #334155; }
            .navbar { background-color: #1e293b; color: #ffffff; padding: 16px 24px; font-size: 18px; font-weight: bold; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
            .main-container { padding: 50px 20px; display: flex; flex-direction: column; align-items: center; }
            .input-card { background-color: #ffffff; width: 100%; max-width: 650px; padding: 30px; border-radius: 8px; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1); border: 1px solid #e2e8f0; }
            .card-title { font-size: 15px; font-weight: bold; color: #1e293b; margin-bottom: 16px; }
            textarea.input-area { width: 100%; height: 180px; padding: 16px; border: 1px dashed #94a3b8; border-radius: 4px; background-color: #fafafa; color: #475569; font-size: 14px; box-sizing: border-box; resize: vertical; outline: none; transition: border-color 0.2s; }
            textarea.input-area:focus { border-color: #3b82f6; background-color: #ffffff; }
            
            .btn-group { display: flex; gap: 12px; margin-top: 20px; }
            .reset-btn { background-color: #64748b; color: #ffffff; border: none; padding: 14px 20px; border-radius: 4px; font-size: 15px; font-weight: bold; cursor: pointer; transition: background-color 0.2s; }
            .reset-btn:hover { background-color: #475569; }
            .submit-btn { flex: 1; background-color: #3b82f6; color: #ffffff; border: none; padding: 14px; border-radius: 4px; font-size: 15px; font-weight: bold; cursor: pointer; transition: background-color 0.2s, transform 0.1s; }
            .submit-btn:hover { background-color: #2563eb; } .submit-btn:active { transform: translateY(1px); }
    
            .result-section { display: none; width: 100%; max-width: 1200px; margin-top: 40px; animation: fadeIn 0.5s ease-out; }
            @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
    
            .action-buttons { display: flex; justify-content: flex-end; gap: 10px; margin-bottom: 15px; }
            .action-btn { padding: 8px 16px; border-radius: 4px; font-size: 13px; font-weight: bold; cursor: pointer; border: none; display: flex; align-items: center; gap: 5px; transition: opacity 0.2s; }
            .action-btn:hover { opacity: 0.8; } .btn-pdf { background-color: #ef4444; color: white; } .btn-copy { background-color: #1e293b; color: white; }
    
            .summary-card { background: #ffffff; border-left: 5px solid #3b82f6; padding: 25px; border-radius: 8px; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1); margin-bottom: 25px; }
            .summary-header-row { display: flex; align-items: baseline; flex-wrap: wrap; margin-top: 15px;}
            .summary-card h2 { margin: 0 0 15px 0; font-size: 20px; color: #1e293b; }
            .pace-highlight { font-size: 24px; font-weight: bold; color: #eab308; margin: 10px 0; }
            .race-info-text { color: #dc2626; font-size: 15px; font-weight: bold; margin-left: 15px; }
            .stats-row { display: flex; flex-wrap: wrap; gap: 15px; align-items: center; color: #64748b; font-size: 14px; margin-bottom: 10px; }
            .stats-item strong { color: #1e293b; }
            .stats-highlight { background-color: #eff6ff; padding: 4px 10px; border-radius: 4px; color: #1d4ed8; border: 1px solid #bfdbfe; font-size: 16px; }
            .stats-highlight-win { background-color: #fef2f2; padding: 4px 10px; border-radius: 4px; color: #dc2626; border: 1px solid #fecaca; font-size: 16px; }
    
            .incidents-container { background-color: #fef2f2; border-left: 4px solid #ef4444; padding: 15px 20px; margin: 20px 0; border-radius: 4px; }
            .incidents-container h3 { color: #b91c1c; margin: 0 0 10px 0; font-size: 16px; }
            .incidents-list { margin: 0; padding-left: 20px; color: #7f1d1d; font-size: 14px; line-height: 1.5; }
    
            .halves-comparison { display: flex; justify-content: center; align-items: center; gap: 30px; margin: 20px 0; padding: 15px; background: #f8fafc; border-radius: 8px; border: 1px solid #e2e8f0; }
            .half-box { text-align: center; } .half-label { font-size: 13px; color: #64748b; margin-bottom: 5px; }
            .half-time { font-size: 26px; font-weight: bold; color: #1e293b; } .half-time span { font-size: 16px; color: #64748b; font-weight: normal; }
            .half-divider { color: #94a3b8; font-size: 24px; }
    
            .chart-wrapper { position: relative; margin-top: 20px; }
            .chart-container { position: relative; height: 280px; width: 100%; }
            .chart-labels { position: relative; height: 20px; margin-top: -5px; }
            .label-start { position: absolute; left: 35px; color: #dc2626; font-weight: bold; font-size: 14px; }
            .label-goal { position: absolute; right: 5px; color: #dc2626; font-weight: bold; font-size: 14px; }
    
            .margin-wrapper { width: 100%; margin: 30px 0; border-radius: 8px; box-shadow: inset 0 2px 4px rgba(0,0,0,0.1); overflow: hidden; }
            .margin-track { position: relative; height: 380px; width: 100%; border-radius: 8px; background-image: repeating-linear-gradient(270deg, transparent, transparent 199px, rgba(255,255,255,0.1) 199px, rgba(255,255,255,0.1) 200px); }
            .margin-track-title { position: absolute; top: 10px; left: 15px; color: rgba(255,255,255,0.9); font-size: 14px; font-weight: bold; z-index: 20; pointer-events: none; text-shadow: 1px 1px 3px rgba(0,0,0,0.8); }
            .goal-line { position: absolute; top: 0; bottom: 0; width: 4px; background-color: #ffffff; box-shadow: 0 0 5px rgba(255,255,255,0.8); z-index: 5; }
            .goal-text { position: absolute; top: 15px; color: #ffffff; font-weight: bold; font-size: 18px; letter-spacing: 4px; writing-mode: vertical-rl; z-index: 5; text-shadow: 1px 1px 3px rgba(0,0,0,0.8); }
            .horse-icon-wrapper { position: absolute; display: flex; flex-direction: column; align-items: center; z-index: 15; width: 50px; margin-left: -25px; transition: all 0.3s ease; }
            .horse-box { width: 28px; height: 28px; border-radius: 4px; display: flex; align-items: center; justify-content: center; font-weight: bold; font-size: 13px; box-shadow: 0 2px 4px rgba(0,0,0,0.5); }
            .horse-name-mini { color: #ffffff; font-size: 10px; margin-top: 2px; white-space: nowrap; text-shadow: 1px 1px 2px #000000; background: rgba(0,0,0,0.4); padding: 1px 4px; border-radius: 3px; }
    
            .payout-card { background: #ffffff; border-radius: 8px; padding: 20px; margin: 25px 0; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1); border-top: 4px solid #10b981; }
            .payout-card h3 { margin: 0 0 15px 0; font-size: 16px; color: #065f46; display: flex; align-items: center; gap: 6px; }
            .payout-grid-new { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 15px; }
            .payout-table { width: 100%; border-collapse: collapse; font-size: 13px; background: #ffffff; box-shadow: 0 1px 3px rgba(0,0,0,0.1); border-radius: 4px; overflow: hidden; }
            .payout-table th, .payout-table td { border: 1px solid #e2e8f0; padding: 8px; text-align: right; vertical-align: middle; }
            .payout-table th { background-color: #f8fafc; color: #475569; text-align: center; width: 60px; font-weight: bold; }
            .payout-table td.combo { text-align: center; font-weight: bold; color: #1e293b; letter-spacing: 1px; width: 80px; }
            .payout-table td.yen { color: #dc2626; font-weight: bold; }
            .payout-table td.pop { color: #64748b; font-size: 11px; width: 60px; white-space: nowrap; }
    
            .top-horses-memo { background: #fffbdd; border-left: 4px solid #f1c40f; padding: 15px 20px; border-radius: 4px; margin: 20px 0; }
            .top-horses-memo h3 { margin: 0 0 12px 0; font-size: 16px; color: #b7950b; }
            .memo-item { margin-bottom: 8px; font-size: 14px; color: #333; line-height: 1.5; }
    
            .table-responsive { background: #ffffff; border-radius: 8px; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1); overflow-x: auto; padding: 20px; }
            table#resultTable { width: 100%; border-collapse: collapse; font-size: 13px; white-space: nowrap; }
            table#resultTable th, table#resultTable td { border-bottom: 1px solid #e2e8f0; padding: 12px 10px; text-align: center; vertical-align: top;}
            table#resultTable th { background-color: #f8fafc; color: #475569; font-weight: bold; border-top: 1px solid #e2e8f0; }
            table#resultTable tr:hover td { background-color: #f1f5f9; }
            
            .target-badge { display: inline-block; background-color: #ef4444; color: white; padding: 2px 6px; border-radius: 4px; font-size: 11px; margin-left: 8px; font-weight: bold; box-shadow: 0 2px 4px rgba(239,68,68,0.3); animation: pulse 2s infinite; }
            .badge-gekiatsu { background-color: #eab308; color: #111827; }
            .badge-kiken { background-color: #64748b; }
            .badge-oana { background-color: #8b5cf6; }
            @keyframes pulse { 0% { transform: scale(1); } 50% { transform: scale(1.05); } 100% { transform: scale(1); } }
            
            .score-legend { color: #ef4444; text-shadow: 0 0 5px rgba(239,68,68,0.3); font-size: 18px; font-weight: 900; }
            .score-high { color: #dc2626; font-weight: bold; font-size: 17px; }
            .score-mid { color: #d97706; font-weight: bold; font-size: 16px; }
            .score-low { color: #64748b; font-size: 15px; }
            .pop-good { color: #dc2626; font-weight: bold; } .pop-bad { color: #3b82f6; }
    
            /* メモ編集エリア・マイクボタンのスタイル */
            .memo-cell { text-align: left; min-width: 250px; color: #334155; }
            .editable-memo { padding: 4px; border-radius: 4px; border-bottom: 1px dashed #cbd5e1; outline: none; transition: background-color 0.2s; font-weight: 600; line-height: 1.5; cursor: text; margin-bottom: 8px;}
            .editable-memo:focus { background-color: #fffbdd; border-bottom: 1px solid #eab308; }
            
            .memo-controls { display: flex; gap: 8px; align-items: center; }
            .badge-select { padding: 2px 4px; font-size: 11px; border: 1px solid #cbd5e1; border-radius: 4px; background: white; color: #475569; cursor: pointer; }
            .mic-btn { background: #ffffff; border: 1px solid #cbd5e1; border-radius: 50%; cursor: pointer; font-size: 12px; width: 24px; height: 24px; display: flex; align-items: center; justify-content: center; transition: all 0.2s; flex-shrink: 0; box-shadow: 0 1px 2px rgba(0,0,0,0.1); }
            .mic-btn:hover { background-color: #f8fafc; border-color: #94a3b8; transform: scale(1.05); }
            .mic-active { background-color: #ef4444 !important; color: white !important; border-color: #dc2626 !important; animation: pulse 1s infinite; }
            
            /* スコア直接編集のスタイル */
            .score-input { width: 45px; text-align: center; border: none; border-bottom: 1px dashed #cbd5e1; background-color: transparent; font-family: inherit; outline: none; transition: background-color 0.2s; }
            .score-input:focus { background-color: #fffbdd; border-bottom: 1px solid #eab308; }
            .score-input::-webkit-outer-spin-button, .score-input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; }
            .score-input[type=number] { -moz-appearance: textfield; }
    
            /* 画像アップロード関連スタイル */
            .image-cell { text-align: center; vertical-align: middle; width: 130px; }
            .img-upload-btn { background: #f8fafc; border: 1px solid #cbd5e1; border-radius: 4px; padding: 4px 8px; font-size: 12px; cursor: pointer; color: #475569; transition: all 0.2s; }
            .img-upload-btn:hover { background: #e2e8f0; color: #1e293b; }
            .img-preview { max-width: 120px; max-height: 80px; border-radius: 4px; box-shadow: 0 1px 3px rgba(0,0,0,0.2); cursor: pointer; border: 1px solid #cbd5e1; transition: transform 0.2s; }
            .img-preview:hover { transform: scale(1.05); }
        </style>
    </head>
    <body>
    
    <nav class="navbar">Analytics Dash PRO (JRA専用)</nav>
    <div class="main-container">
        <div class="input-card" id="inputContainer">
            <div class="card-title">出馬表・レース結果データ読み込み (JRA専用)</div>
            <textarea id="inputData" class="input-area" placeholder="JRA公式のレース結果テキストを全選択してペースト..."></textarea>
            <div class="btn-group">
                <button class="reset-btn" onclick="resetDashboard()">クリア</button>
                <button class="submit-btn" onclick="analyzeRace()">ダッシュボードを生成 (AI自動分析)</button>
            </div>
        </div>
    
        <div id="resultSection" class="result-section">
            <div class="action-buttons" data-html2canvas-ignore="true">
                <button class="action-btn btn-copy" onclick="copySummaryText()">📋 テキストを完全コピー</button>
                <button class="action-btn btn-pdf" onclick="downloadPDF()">📄 PDFで保存</button>
            </div>
            <div id="pdfContentArea">
                <div class="summary-card">
                    <h2>📊 レース展開分析ダッシュボード</h2>
                    <div class="stats-row">
                        <div class="stats-item">レース距離: <strong id="outDist"></strong>m</div>
                        <div class="stats-item">レース勝ち時計: <strong id="outWinTime" class="stats-highlight-win"></strong></div>
                        <div class="stats-item">基準タイム (TARGET換算): <strong id="outStdTime" class="stats-highlight"></strong></div>
                    </div>
                    <div class="summary-header-row">
                        <div class="pace-highlight" id="outPaceType"></div>
                        <div class="race-info-text" id="outRaceInfo"></div>
                    </div>
                    <div style="margin-top:5px; padding:10px; background:#f8fafc; border-left:4px solid #3b82f6; border-radius:4px;">
                        <strong style="color:#1e293b; font-size:14px;">📝 タイムレベル評価:</strong>
                        <span id="outPaceDesc" style="font-size:14px; color:#475569;"></span>
                    </div>
                    <div id="incidentsSection" class="incidents-container" style="display:none;">
                        <h3>⚠️ 競走中の出来事・制裁等</h3><ul class="incidents-list" id="incidentsList"></ul>
                    </div>
                    <div class="halves-comparison" id="halvesComparison" style="display:none;">
                        <div class="half-box"><div class="half-label">前半 (<span id="halfDistText1"></span>m)</div><div class="half-time" id="firstHalfTime"></div></div>
                        <div class="half-divider">▶</div>
                        <div class="half-box"><div class="half-label">後半 (<span id="halfDistText2"></span>m)</div><div class="half-time" id="secondHalfTime"></div></div>
                    </div>
                    <div class="chart-wrapper" id="chartWrapper" style="display:none;">
                        <div class="chart-container"><canvas id="paceChart"></canvas></div>
                        <div class="chart-labels"><span class="label-start">スタート</span><span class="label-goal">ゴール</span></div>
                    </div>
                    <div class="margin-wrapper" id="marginWrapper" style="display:none;"><div class="margin-track" id="marginTrack"></div></div>
                    <div class="payout-card" id="payoutCard" style="display:none;"></div>
                    <div class="top-horses-memo" id="topHorsesMemo" style="display:none;">
                        <h3>🎯 上位馬 & 次走狙い馬アナリストメモ</h3><div id="topMemoContent"></div>
                    </div>
                </div>
                <div class="table-responsive">
                    <table id="resultTable">
                        <thead>
                            <tr>
                                <th>着順</th><th>馬番</th><th>馬名</th><th>着差</th><th>タイム</th><th>上り3F</th><th>通過順</th><th>馬体重</th><th>人気</th><th>評価スコア<br><small>(直接編集可)</small></th><th>全頭評価 (📝編集・🎙️音声・🏷️バッジ)</th><th>📸 画像メモ</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        let paceChartInstance = null; let currentAnalysisData = {}; 
        const fullStdTimeDb = {
            "中京": { "ダ1200m": { "新馬": 73.6, "未勝利": 72.8, "1勝": 71.8, "2勝": 71.4, "3勝": 71.6 }, "ダ1400m": { "新馬": 86.3, "未勝利": 85.3, "1勝": 84.9, "2勝": 84.4, "3勝": 83.8, "OP": 82.7 }, "ダ1800m": { "新馬": 115.3, "未勝利": 114.6, "1勝": 113.5, "2勝": 113.2, "3勝": 112.4, "OP": 111.2 }, "ダ1900m": { "未勝利": 121.3, "1勝": 120.2, "2勝": 119.6, "3勝": 118.6 }, "芝1200m/内": { "新馬": 68.8, "未勝利": 68.8, "1勝": 68.8, "2勝": 68.6, "3勝": 68.0, "OP": 68.2 }, "芝1400m/内": { "新馬": 82.0, "未勝利": 81.5, "1勝": 80.5, "2勝": 81.3, "3勝": 80.1, "OP": 80.4 }, "芝1600m/内": { "新馬": 96.2, "未勝利": 94.4, "1勝": 94.5, "2勝": 94.3, "3勝": 94.8, "OP": 93.5 }, "芝2000m/内": { "新馬": 123.1, "未勝利": 121.2, "1勝": 120.4, "2勝": 120.6, "3勝": 119.9, "OP": 120.4 }, "芝2200m/内": { "未勝利": 134.5, "1勝": 133.3, "2勝": 133.2, "OP": 129.8 }, "芝3000m/内": { "OP": 190.2 } },
            "中山": { "ダ1200m": { "新馬": 72.7, "未勝利": 72.3, "1勝": 71.5, "2勝": 71.2, "3勝": 70.7, "OP": 70.0 }, "ダ1800m": { "新馬": 116.2, "未勝利": 115.2, "1勝": 114.0, "2勝": 113.4, "3勝": 112.3, "OP": 111.9 }, "ダ2400m": { "1勝": 155.8, "2勝": 155.4 }, "ダ2500m": { "1勝": 163.2 }, "芝1200m外": { "新馬": 69.2, "未勝利": 69.2, "1勝": 68.8, "2勝": 67.8, "3勝": 67.8, "OP": 67.5 }, "芝1600m外": { "新馬": 95.8, "未勝利": 94.5, "1勝": 93.8, "2勝": 93.6, "3勝": 93.1, "OP": 93.4 }, "芝1800m/内": { "新馬": 109.7, "未勝利": 109.5, "1勝": 108.3, "2勝": 109.0, "3勝": 107.0, "OP": 107.7 }, "芝2000m/内": { "新馬": 122.6, "未勝利": 121.3, "1勝": 119.8, "2勝": 119.8, "3勝": 118.9, "OP": 119.5 }, "芝2200m外": { "未勝利": 134.3, "1勝": 133.8, "2勝": 133.0, "3勝": 131.7, "OP": 131.0 }, "芝2500m/内": { "1勝": 152.3, "2勝": 153.1, "3勝": 154.5, "OP": 151.8 }, "芝3600m/内": { "OP": 207.2 } },
            "京都": { "ダ1200m": { "新馬": 73.1, "未勝利": 72.8, "1勝": 71.7, "2勝": 71.3, "3勝": 70.3, "OP": 70.6 }, "ダ1400m": { "新馬": 85.5, "未勝利": 85.1, "1勝": 84.3, "2勝": 83.3, "3勝": 83.2, "OP": 82.8 }, "ダ1800m": { "新馬": 114.3, "1勝": 112.5, "2勝": 111.4, "3勝": 110.4, "OP": 110.0 }, "ダ1900m": { "未勝利": 120.9, "1勝": 120.5, "2勝": 118.5, "3勝": 117.8, "OP": 117.3 }, "芝1200m/内": { "新馬": 70.0, "未勝利": 69.2, "1勝": 69.0, "2勝": 68.7, "3勝": 68.1, "OP": 68.3 }, "芝1400m/内": { "新馬": 81.7, "未勝利": 81.2 }, "芝1400m外": { "1勝": 81.5, "2勝": 80.8, "3勝": 81.4, "OP": 80.7 }, "芝1600m/内": { "新馬": 95.2, "未勝利": 95.1, "1勝": 94.6 }, "芝1600m外": { "1勝": 91.8, "2勝": 94.0, "3勝": 93.3, "OP": 93.0 }, "芝1800m/外": { "新馬": 108.6, "未勝利": 107.8, "1勝": 108.8, "2勝": 108.8, "3勝": 105.7, "OP": 105.9 }, "芝2000m/内": { "新馬": 122.3, "未勝利": 121.6, "1勝": 120.5, "2勝": 120.1, "3勝": 121.7, "OP": 119.7 }, "芝2200m/内": { "未勝利": 135.6, "1勝": 134.1, "2勝": 133.5, "3勝": 135.8, "OP": 133.8 }, "芝2400m/外": { "未勝利": 147.7, "1勝": 148.1, "2勝": 148.1, "3勝": 144.6, "OP": 143.9 }, "芝3000m外": { "3勝": 183.8, "OP": 184.0 }, "芝3200m外": { "OP": 194.0 } },
            "函館": { "ダ1000m": { "新馬": 58.8, "未勝利": 58.9, "1勝": 58.5, "2勝": 58.9 }, "ダ1700m": { "新馬": 106.3, "未勝利": 105.9, "1勝": 105.5, "2勝": 104.7, "OP": 103.5 }, "ダ2400m": { "未勝利": 154.2, "1勝": 154.7 }, "芝1000m/内": { "新馬": 56.4 }, "芝1200m/内": { "新馬": 69.5, "未勝利": 69.0, "1勝": 68.5, "2勝": 68.3, "3勝": 69.0, "OP": 67.7 }, "芝1800m/内": { "新馬": 109.3, "未勝利": 108.1, "1勝": 107.1, "2勝": 106.2, "3勝": 106.3, "OP": 104.8 }, "芝2000m/内": { "未勝利": 120.6, "1勝": 120.3, "2勝": 119.4 }, "芝2600m/内": { "未勝利": 158.6, "2勝": 157.5, "OP": 157.6 } },
            "小倉": { "ダ1000m": { "新馬": 61.5, "未勝利": 58.7, "1勝": 58.7, "2勝": 57.9, "3勝": 59.0 }, "ダ1700m": { "未勝利": 106.8, "1勝": 106.6, "2勝": 105.5, "3勝": 104.0, "OP": 103.7 }, "ダ2400m": { "1勝": 151.1 }, "芝1200m/内": { "新馬": 70.7, "未勝利": 69.1, "1勝": 69.1, "2勝": 68.5, "3勝": 68.5, "OP": 68.9 }, "芝1700m/内": { "新馬": 101.0, "未勝利": 100.1, "1勝": 100.1, "2勝": 100.5, "3勝": 100.5, "OP": 101.9 }, "芝1800m/内": { "新馬": 110.9, "1勝": 110.0, "2勝": 108.3, "3勝": 108.6, "3勝_2": 107.0, "OP": 106.1 }, "芝2000m/内": { "新馬": 123.4, "未勝利": 121.9, "1勝": 121.4, "2勝": 121.7, "3勝": 124.4, "OP": 119.9 }, "芝2600m/内": { "未勝利": 164.4, "1勝": 161.8, "2勝": 158.4 } },
            "新潟": { "ダ1700m": { "新馬": 112.9, "未勝利": 111.9, "1勝": 111.6, "2勝": 110.8, "3勝": 110.8, "OP": 110.8 }, "ダ1800m": { "新馬": 118.0, "未勝利": 114.9, "1勝": 113.3, "2勝": 112.8, "3勝": 111.9, "OP": 110.9 }, "ダ2500m": { "1勝": 161.8 }, "芝1000m/内": { "未勝利": 58.7, "1勝": 58.7, "2勝": 58.7, "3勝": 55.1, "OP": 54.8 }, "芝1200m/内": { "新馬": 69.8, "未勝利": 70.1, "1勝": 70.2, "2勝": 68.8, "3勝": 68.0 }, "芝1400m/内": { "新馬": 82.5, "未勝利": 82.1, "1勝": 82.2, "2勝": 80.5, "3勝": 79.1, "OP": 81.4 }, "芝1600m/内": { "新馬": 96.7, "未勝利": 95.0, "1勝": 93.8, "2勝": 93.8, "3勝": 93.5, "OP": 93.2 }, "芝1800m/内": { "新馬": 109.0, "未勝利": 108.0, "1勝": 107.7, "2勝": 106.5, "3勝": 108.1, "OP": 106.2 }, "芝2000m/内": { "新馬": 123.9, "未勝利": 122.6 }, "芝2000m外": { "1勝": 120.9, "2勝": 121.0, "3勝": 118.2, "OP": 119.7 }, "芝2200m/内": { "未勝利": 135.0, "1勝": 133.5, "2勝": 134.3, "3勝": 132.1, "OP": 132.7 }, "芝2400m/内": { "未勝利": 148.3, "1勝": 145.4 } },
            "札幌": { "ダ1000m": { "新馬": 58.2, "未勝利": 58.2, "1勝": 58.6, "2勝": 58.7 }, "ダ1700m": { "新馬": 106.3, "未勝利": 106.2, "1勝": 105.5, "2勝": 104.6, "3勝": 103.5, "OP": 103.5 }, "ダ2400m": { "未勝利": 157.2, "1勝": 154.6 }, "芝1200m/内": { "新馬": 69.8, "未勝利": 69.8, "1勝": 68.3, "2勝": 69.0, "3勝": 67.4, "OP": 69.4 }, "芝1500m/内": { "新馬": 90.2, "未勝利": 89.8, "1勝": 89.1, "2勝": 88.3, "3勝": 89.5, "OP": 89.7 }, "芝1800m/内": { "新馬": 111.0, "未勝利": 109.8, "1勝": 106.8, "2勝": 108.5 }, "芝2000m/内": { "新馬": 124.5, "未勝利": 122.5, "1勝": 121.0, "2勝": 121.3, "3勝": 121.2, "OP": 121.2 }, "芝2600m/内": { "未勝利": 162.8, "1勝": 161.8, "2勝": 161.6, "OP": 161.2 } },
            "東京": { "ダ1300m": { "新馬": 78.5, "未勝利": 78.9, "1勝": 78.5, "2勝": 77.7, "3勝": 76.5 }, "ダ1400m": { "新馬": 86.1, "未勝利": 85.6, "1勝": 84.4, "2勝": 83.9, "3勝": 83.3, "OP": 83.0 }, "ダ1600m": { "新馬": 99.7, "未勝利": 97.9, "1勝": 97.1, "2勝": 96.5, "3勝": 95.5, "OP": 95.5 }, "ダ2100m": { "未勝利": 133.0, "1勝": 131.6, "2勝": 131.0, "3勝": 130.6, "OP": 129.1 }, "芝1400m/内": { "新馬": 83.1, "未勝利": 82.2, "1勝": 81.5, "2勝": 80.9, "3勝": 80.7, "OP": 80.7 }, "芝1600m/内": { "新馬": 95.2, "未勝利": 94.4, "1勝": 93.5, "2勝": 93.7, "3勝": 93.3, "OP": 92.5 }, "芝1800m/内": { "新馬": 108.4, "未勝利": 107.5, "1勝": 106.3, "2勝": 106.5, "3勝": 105.5, "OP": 105.8 }, "芝2000m/内": { "新馬": 121.8, "未勝利": 120.6, "1勝": 120.0, "2勝": 120.0, "3勝": 118.1, "OP": 118.6 }, "芝2400m/内": { "未勝利": 148.2, "1勝": 146.4, "2勝": 145.6, "3勝": 146.3, "OP": 143.7 }, "芝2500m/内": { "OP": 151.4 }, "芝3400m/内": { "OP": 212.2 } },
            "福島": { "ダ1150m": { "新馬": 70.2, "未勝利": 69.1, "1勝": 68.9, "2勝": 68.5, "3勝": 68.3, "OP": 67.3 }, "ダ1700m": { "新馬": 107.7, "未勝利": 107.6, "1勝": 106.3, "2勝": 105.8, "3勝": 105.5, "OP": 104.5 }, "ダ2400m": { "1勝": 154.6 }, "芝1200m/内": { "新馬": 70.7, "未勝利": 69.5, "1勝": 69.0, "2勝": 68.6, "3勝": 69.4, "OP": 68.9 }, "芝1800m/内": { "新馬": 111.8, "未勝利": 109.4, "1勝": 107.6, "2勝": 107.8, "3勝": 106.9, "OP": 106.6 }, "芝2000m/内": { "新馬": 124.9, "未勝利": 121.9, "1勝": 120.3, "2勝": 122.5, "3勝": 119.3, "OP": 120.1 }, "芝2600m/内": { "未勝利": 161.2, "1勝": 161.1, "2勝": 162.1 } },
            "阪神": { "ダ1200m": { "新馬": 73.9, "未勝利": 73.1, "1勝": 72.3, "2勝": 71.1, "3勝": 70.9, "OP": 70.8 }, "ダ1400m": { "新馬": 86.0, "未勝利": 85.7, "1勝": 84.8, "2勝": 84.2, "3勝": 84.0, "OP": 83.7 }, "ダ1800m": { "新馬": 115.0, "未勝利": 115.1, "1勝": 113.8, "2勝": 113.0, "3勝": 112.7, "OP": 111.0 }, "ダ2000m": { "未勝利": 129.2, "1勝": 126.9, "2勝": 126.1, "3勝": 125.5, "OP": 124.7 }, "芝1200m/内": { "新馬": 70.4, "未勝利": 69.0, "1勝": 68.8, "2勝": 68.6, "3勝": 68.1, "OP": 67.8 }, "芝1400m/内": { "新馬": 82.5, "未勝利": 81.4, "1勝": 80.5, "2勝": 80.2, "3勝": 80.6, "OP": 79.8 }, "芝1600m外": { "新馬": 95.8, "未勝利": 94.0, "1勝": 93.9, "2勝": 93.8, "3勝": 92.4, "OP": 92.9 }, "芝1800m外": { "新馬": 108.3, "未勝利": 107.1, "1勝": 106.0, "2勝": 105.4, "3勝": 104.8, "OP": 104.4 }, "芝2000m/内": { "新馬": 123.4, "未勝利": 121.5, "1勝": 120.1, "2勝": 120.0, "3勝": 119.2, "OP": 119.2 }, "芝2200m/内": { "未勝利": 133.6, "1勝": 133.0, "2勝": 131.8, "3勝": 131.8, "OP": 131.1 }, "芝2400m/内": { "未勝利": 148.0, "1勝": 145.5, "2勝": 145.0, "3勝": 144.1, "OP": 146.4 }, "芝2600m/内": { "2勝": 159.1, "OP": 159.8 }, "芝3000m/内": { "3勝": 182.9, "OP": 183.3 } }
        };
    
        function parseTime(timeStr) {
            if (!timeStr || timeStr === "-") return 0;
            let parts = timeStr.split(':');
            if(parts.length === 2) { return parseInt(parts[0]) * 60 + parseFloat(parts[1]); }
            return parseFloat(timeStr);
        }
    
        function getStandardTimeObj(dist, trackType, trackCond, classInfo, locName) {
            let normalizedClass = "未勝利";
            if (classInfo.includes("1勝") || classInfo.includes("1勝") || classInfo.includes("C1") || classInfo.includes("C1")) normalizedClass = "1勝";
            else if (classInfo.includes("2勝") || classInfo.includes("2勝") || classInfo.includes("B") || classInfo.includes("B")) normalizedClass = "2勝";
            else if (classInfo.includes("3勝") || classInfo.includes("3勝") || classInfo.includes("オープン") || classInfo.includes("重賞") || classInfo.includes("A") || classInfo.includes("A") || classInfo.includes("G") || classInfo.includes("G")) normalizedClass = "OP";
            else if (classInfo.includes("新馬")) normalizedClass = "新馬";
            
            let typeKey = trackType.includes("ダート") ? "ダ" : "芝";
            let t = 0; let found = false;
    
            if (locName && fullStdTimeDb[locName]) {
                let courseDict = fullStdTimeDb[locName];
                for (let trackKey in courseDict) {
                    if (trackKey.startsWith(typeKey) && trackKey.includes(dist + "m")) {
                        let clsData = courseDict[trackKey];
                        if (clsData[normalizedClass] !== undefined) { t = clsData[normalizedClass]; found = true; break; }
                        else if (clsData["OP"] !== undefined) { t = clsData["OP"]; found = true; break; }
                        else if (clsData["未勝利"] !== undefined) { t = clsData["未勝利"]; found = true; break; }
                    }
                }
                if (!found) {
                    for (let trackKey in courseDict) {
                        if (trackKey.includes(dist + "m")) {
                            let clsData = courseDict[trackKey];
                            let availableVals = Object.values(clsData);
                            if (availableVals.length > 0) { t = availableVals[0]; found = true; break; }
                        }
                    }
                }
            }
            if (!found || t === 0) { t = typeKey === "ダ" ? dist * 0.063 : dist * 0.059; }
            if (typeKey === "芝") {
                if (trackCond.includes("稍重")) t += 0.8; else if (trackCond.includes("重")) t += 1.5; else if (trackCond.includes("不良")) t += 2.5;
            } else {
                if (trackCond.includes("稍重")) t -= 0.5; else if (trackCond.includes("重")) t -= 1.0; else if (trackCond.includes("不良")) t -= 0.5;
            }
            let m = Math.floor(t / 60); let s = (t % 60).toFixed(1);
            let str = m > 0 ? `${m}:${s.padStart(4, '0')}` : `0:${s.padStart(4, '0')}`;
            return { str: str, sec: t };
        }
    
        function parseMarginToLengths(marginStr) {
            if (!marginStr || marginStr === "-") return 0;
            if (marginStr.includes("同着")) return 0;
            if (marginStr.includes("ハナ")) return 0.05;
            if (marginStr.includes("アタマ")) return 0.1;
            if (marginStr.includes("クビ")) return 0.25;
            if (marginStr.includes("大差")) return 10.0;
            let s = marginStr.replace(/[0-9]/g, c => String.fromCharCode(c.charCodeAt(0) - 0xFEE0)).replace(///g, '/');
            let parts = s.trim().split(/\s+/); let len = 0;
            for (let p of parts) {
                if (p.includes('/')) {
                    let [num, den] = p.split('/');
                    if (num && den) len += parseInt(num) / parseInt(den);
                } else { let n = parseFloat(p); if (!isNaN(n)) len += n; }
            }
            return len;
        }
    
        function renderMarginVisualizer(horses, rawText, trackType) {
            const track = document.getElementById('marginTrack');
            const wrapper = document.getElementById('marginWrapper');
            if (!horses || horses.length === 0) { wrapper.style.display = 'none'; return; }
    
            let isRightGoal = true;
            if (rawText.includes("左")) isRightGoal = true; 
            if (rawText.includes("右") || rawText.includes("直線")) isRightGoal = false; 
    
            let isDirt = trackType === "ダート";
            let isRainy = rawText.includes("重") || rawText.includes("不良") || rawText.includes("雨");
    
            track.style.backgroundColor = isDirt ? "#713f12" : "#166534";
            let trackHTML = `<div class="margin-track-title">🏁 ゴール前 着差シミュレーター</div>
                <div class="goal-line" style="${isRightGoal ? 'right' : 'left'}: 5%;"></div>
                <div class="goal-text" style="${isRightGoal ? 'right: calc(5% + 8px);' : 'left: calc(5% - 20px);'}">ゴール</div>`;
            if (isRainy) { trackHTML += `<div class="rain-fx"></div>`; }
    
            let sortedHorses = [...horses].sort((a,b) => a.rank - b.rank);
            let cumulativeLengths = 0;
            sortedHorses[0].pxBehind = 0; 
    
            for(let i=1; i<sortedHorses.length; i++) {
                let h = sortedHorses[i];
                let prev = sortedHorses[i-1];
                if (h.rank === prev.rank) {
                    h.pxBehind = prev.pxBehind; 
                } else {
                    let lengths = parseMarginToLengths(h.margin);
                    if (lengths === 0 && h.timeSec > prev.timeSec) { lengths = (h.timeSec - prev.timeSec) * 6; }
                    cumulativeLengths += lengths; 
                    h.pxBehind = cumulativeLengths;
                }
            }
    
            let maxLengths = Math.max(5, cumulativeLengths + 1.5); 
    
            const frameColors = {
                1: { bg: '#ffffff', color: '#1e293b', border: '#cbd5e1' }, 2: { bg: '#1e293b', color: '#ffffff', border: '#1e293b' },
                3: { bg: '#ef4444', color: '#ffffff', border: '#ef4444' }, 4: { bg: '#3b82f6', color: '#ffffff', border: '#3b82f6' },
                5: { bg: '#eab308', color: '#ffffff', border: '#eab308' }, 6: { bg: '#22c55e', color: '#ffffff', border: '#22c55e' },
                7: { bg: '#f97316', color: '#ffffff', border: '#f97316' }, 8: { bg: '#ec4899', color: '#ffffff', border: '#ec4899' }
            };
    
            const totalHorses = sortedHorses.length;
            const laneStep = Math.min(32, 280 / Math.max(1, totalHorses - 1));
    
            sortedHorses.forEach((h, idx) => {
                let percentBehind = (h.pxBehind / maxLengths) * 85; 
                const posStyle = isRightGoal ? `right: calc(5% + ${percentBehind}%);` : `left: calc(5% + ${percentBehind}%);`;
                const numVal = parseInt(h.number) || (idx + 1);
                const topPos = 45 + (numVal - 1) * laneStep; 
    
                let frameNum = h.frame;
                if (!frameNum) {
                    if (totalHorses <= 8) frameNum = h.number;
                    else frameNum = Math.ceil((h.number / totalHorses) * 8);
                    if (frameNum > 8) frameNum = 8;
                }
                const colors = frameColors[frameNum] || frameColors[1];
    
                trackHTML += `
                    <div class="horse-icon-wrapper" style="${posStyle} top: ${topPos}px; z-index: ${30 - h.rank};">
                        <div class="horse-box" style="background-color: ${colors.bg}; color: ${colors.color}; border: 1px solid ${colors.border};">${h.number}</div>
                        <div class="horse-name-mini">${h.name.substring(0, 5)}</div>
                    </div>`;
            });
            track.innerHTML = trackHTML;
            wrapper.style.display = 'block';
        }
    
        function parseAndRenderPayouts(lines) {
            const payoutCard = document.getElementById("payoutCard");
            let payoutData = []; let currentTypeObj = null; let inPayoutSection = false;
            const typeRegex = /^(単勝|複勝|枠複|枠連|馬複|馬連|ワイド|馬単|三連複|3連複|3連複|三連単|3連単|3連単)$/;
    
            for (let i = 0; i < lines.length; i++) {
                let line = lines[i].trim();
                if (!line) continue;
                if (line === "払戻金" || line.includes("払戻金")) { inPayoutSection = true; continue; }
                if (inPayoutSection) {
                    let typeMatch = line.match(typeRegex);
                    if (typeMatch) {
                        let typeName = typeMatch[1].replace(/[3三]/g, '3').replace('枠複', '枠連').replace('馬複', '馬連');
                        currentTypeObj = { type: typeName, rows: [] };
                        payoutData.push(currentTypeObj);
                        continue;
                    }
                    if (currentTypeObj) {
                        let valMatch = line.match(/^([\d-]+)\s+([\d,]+円)\s*(\d+)番人気/);
                        if (valMatch) {
                            currentTypeObj.rows.push({ combo: valMatch[1], yen: valMatch[2], pop: valMatch[3] + "番人気" });
                        } else {
                            let valMatch2 = line.match(/^([\d-]+)\s+([\d,]+円)/);
                            if (valMatch2) { currentTypeObj.rows.push({ combo: valMatch2[1], yen: valMatch2[2], pop: "-" }); }
                            else if (line.startsWith("・") || line.includes("コーナー通過順位") || line.includes("勝馬")) {
                                inPayoutSection = false; currentTypeObj = null;
                            }
                        }
                    }
                }
            }
    
            if (payoutData.length > 0) {
                let html = `<div class="payout-grid-new">`;
                payoutData.forEach(p => {
                    if (p.rows.length === 0) return;
                    html += `<table class="payout-table"><tr><th rowspan="${p.rows.length}">${p.type}</th><td class="combo">${p.rows[0].combo}</td><td class="yen">${p.rows[0].yen}</td><td class="pop">${p.rows[0].pop}</td></tr>`;
                    for(let i=1; i<p.rows.length; i++) { html += `<tr><td class="combo">${p.rows[i].combo}</td><td class="yen">${p.rows[i].yen}</td><td class="pop">${p.rows[i].pop}</td></tr>`; }
                    html += `</table>`;
                });
                html += `</div>`;
                payoutCard.innerHTML = `<h3>💰 払戻金</h3>` + html;
                payoutCard.style.display = "block";
            } else { payoutCard.style.display = "none"; }
        }
    
        function resetDashboard() {
            document.getElementById("inputData").value = "";
            document.getElementById("resultSection").style.display = "none";
            if (paceChartInstance) { paceChartInstance.destroy(); paceChartInstance = null; }
            currentAnalysisData = {};
        }
    
        function startDictation(btn, number) {
            if (!('webkitSpeechRecognition' in window)) {
                alert("お使いのブラウザは音声入力に対応していません。Google Chromeなどをご利用ください。"); return;
            }
            const recognition = new webkitSpeechRecognition();
            recognition.lang = 'ja-JP'; recognition.interimResults = false; recognition.maxAlternatives = 1;
    
            const memoDiv = document.querySelector(`.editable-memo[data-number='${number}']`);
            btn.classList.add("mic-active"); btn.innerHTML = '🎙️';
    
            recognition.onresult = function(event) {
                const result = event.results[0][0].transcript;
                memoDiv.innerText += (memoDiv.innerText ? " " : "") + result;
                updateAnalysisDataMemo(number, memoDiv.innerText);
                updateTopMemoDisplay();
            };
            recognition.onerror = function(event) { console.error("Speech recognition error", event.error); };
            recognition.onend = function() { btn.classList.remove("mic-active"); btn.innerHTML = '🎙️'; };
            recognition.start();
        }
    
        function handleMemoInput(element, number) {
            updateAnalysisDataMemo(number, element.innerText);
            updateTopMemoDisplay();
        }
    
        function updateAnalysisDataMemo(number, text) {
            if (currentAnalysisData.allHorses) {
                let h = currentAnalysisData.allHorses.find(x => x.number == number);
                if (h) h.memo = text;
            }
        }
    
        // 🏆 評価スコアの手動編集機能
        function handleScoreInput(inputElement, number) {
            let val = parseInt(inputElement.value);
            if (isNaN(val)) val = 60;
            if (val > 100) val = 100;
            if (val < 0) val = 0;
            inputElement.value = val;
    
            if (currentAnalysisData.allHorses) {
                let h = currentAnalysisData.allHorses.find(x => x.number == number);
                if (h) h.score = val;
            }
    
            // スコアに合わせて色を動的変更
            inputElement.classList.remove("score-high", "score-mid", "score-low", "score-legend");
            if (val >= 95) inputElement.classList.add("score-legend");
            else if (val >= 80) inputElement.classList.add("score-high");
            else if (val >= 70) inputElement.classList.add("score-mid");
            else inputElement.classList.add("score-low");
    
            updateTopMemoDisplay();
        }
    
        function updateBadge(selectElement, number) {
            if (currentAnalysisData.allHorses) {
                let h = currentAnalysisData.allHorses.find(x => x.number == number);
                if (h) { h.badgeStr = selectElement.value; }
            }
            updateTopMemoDisplay();
        }
    
        function updateTopMemoDisplay() {
            if (!currentAnalysisData.allHorses) return;
            let topMemoHTML = "";
            
            let summaryTargets = currentAnalysisData.allHorses.filter(h => h.badgeStr !== "" || h.rank === 1).sort((a,b) => a.rank - b.rank);
            
            summaryTargets.forEach(h => {
                let badgeHtml = "";
                if (h.badgeStr === "🔥激アツ") badgeHtml = `<span class="target-badge badge-gekiatsu">🔥激アツ</span>`;
                else if (h.badgeStr === "🎯次走注目") badgeHtml = `<span class="target-badge">🎯次走注目</span>`;
                else if (h.badgeStr === "⚠️危険な人気馬") badgeHtml = `<span class="target-badge badge-kiken">⚠️危険な人気馬</span>`;
                else if (h.badgeStr === "🐎大穴狙い") badgeHtml = `<span class="target-badge badge-oana">🐎大穴狙い</span>`;
    
                topMemoHTML += `<div class="memo-item"><strong>${h.rank}着 ${h.name} <span style="font-size:12px; color:#94a3b8;">[${h.score}点]</span> ${badgeHtml}</strong>:<br>${h.memo}</div>`; 
            });
            
            if (topMemoHTML) {
                document.getElementById("topMemoContent").innerHTML = topMemoHTML;
                document.getElementById("topHorsesMemo").style.display = "block";
            } else {
                document.getElementById("topHorsesMemo").style.display = "none";
            }
        }
    
        function previewImage(input, number) {
            if (input.files && input.files[0]) {
                let reader = new FileReader();
                reader.onload = function(e) {
                    if (currentAnalysisData.allHorses) {
                        let h = currentAnalysisData.allHorses.find(x => x.number == number);
                        if(h) h.imageData = e.target.result;
                    }
                    let container = document.getElementById(`img-preview-container-${number}`);
                    container.innerHTML = `<img src="${e.target.result}" class="img-preview" onclick="removeImage(${number})" title="クリックで削除">`;
                    
                    let btn = container.nextElementSibling;
                    if (btn) { btn.innerHTML = "🔄 変更"; btn.style.fontSize = "10px"; btn.style.marginTop = "4px"; }
                }
                reader.readAsDataURL(input.files[0]);
            }
        }
    
        function removeImage(number) {
            if(confirm("この画像を削除しますか?")) {
                if (currentAnalysisData.allHorses) {
                    let h = currentAnalysisData.allHorses.find(x => x.number == number);
                    if(h) h.imageData = null;
                }
                let container = document.getElementById(`img-preview-container-${number}`);
                container.innerHTML = "";
                let input = document.getElementById(`img-input-${number}`); input.value = "";
                
                let btn = container.nextElementSibling;
                if (btn) { btn.innerHTML = "📸 画像追加"; btn.style.fontSize = "12px"; btn.style.marginTop = "0"; }
            }
        }
    
        function analyzeRace() {
            const btn = document.querySelector('.submit-btn');
            btn.innerText = "分析中..."; btn.style.backgroundColor = "#94a3b8";
            setTimeout(() => {
                processData();
                btn.innerText = "ダッシュボードを生成 (AI自動分析)"; btn.style.backgroundColor = "#3b82f6";
            }, 300);
        }
    
        function processData() {
            const text = document.getElementById("inputData").value;
            if(!text) { alert("出馬表データを貼り付けてください。"); return; }
    
            let lines = text.split('\n').map(x => x.trim());
            let horses = []; let incidents = []; let currentHorse = null; let raceSplits = [];
            
            let distMatch = text.match(/(\d{1,3}(?:,\d{3})*)メートル/) || text.match(/([ダ芝]?\s*[\d,]+)\s*(?:m|メートル)/);
            let distance = 0;
            if (distMatch) { distance = parseInt((distMatch[1] || distMatch[2]).replace(/[^\d]/g, '')); }
            if(distance === 0) { alert("距離データが見つかりません。テキストが全てコピーされているか確認してください。"); return; }
    
            let locName = "", raceNum = "", trackType = "", trackCond = "", classInfo = "";
            let excludeIncidentKws = ["勝馬投票に的中", "特定の馬番・組番", "つく記号", "特払い", "JRAプラス10", "レコードタイム", "払戻金", "コーナー通過", "出馬表", "オッズ", "レース結果の見方", "コース:"];
            let classKeywords = ["未勝利", "1勝クラス", "1勝クラス", "2勝クラス", "2勝クラス", "3勝クラス", "3勝クラス", "オープン", "新馬", "GⅠ", "GⅡ", "GⅢ", "G1", "G2", "G3", "リステッド", "重賞"];
    
            let locMatch = text.match(/20\d{2}年.*?回(東京|中山|阪神|京都|中京|新潟|福島|小倉|札幌|函館)\d+日/);
            if (locMatch) { locName = locMatch[1]; } 
            else {
                let locList = ["東京", "中山", "阪神", "京都", "中京", "新潟", "福島", "小倉", "札幌", "函館"];
                for(let loc of locList) { if (text.includes(loc)) { locName = loc; break; } }
            }
    
            for(let i=0; i<lines.length; i++) {
                let line = lines[i];
                let rNumMatch = line.match(/(\d+)レース|第(\d+)日|(\d+)R/);
                if(rNumMatch && !raceNum) raceNum = (rNumMatch[1] || rNumMatch[2] || rNumMatch[3]) + "R";
                
                let trackMatch = line.match(/(芝|ダート|ダ)\s*(良|稍重|重|不良)?/);
                if(trackMatch && !trackType) { trackType = trackMatch[1].includes("ダ") ? "ダート" : "芝"; if (trackMatch[2]) trackCond = trackMatch[2]; }
    
                let condMatch = line.match(/馬場:\s*(ダート|芝)?\s*(良|稍重|重|不良)/);
                if(condMatch) { if (condMatch[1]) trackType = condMatch[1]; trackCond = condMatch[2]; }
    
                if(!classInfo) {
                    for(let kw of classKeywords) { if (line.includes(kw) && !line.includes("コース:")) { classInfo = kw; break; } }
                }
                if (line.startsWith("・")) {
                    if (!excludeIncidentKws.some(kw => line.includes(kw))) incidents.push(line.substring(1).trim());
                }
            }
            
            let headerInfos = [];
            if(locName) headerInfos.push(locName + (raceNum ? raceNum : ""));
            if(classInfo) headerInfos.push(classInfo);
            if(trackType && trackCond) headerInfos.push(`${trackType}・${trackCond}`);
            let finalRaceInfoStr = headerInfos.join(", ");
            document.getElementById("outRaceInfo").innerText = finalRaceInfoStr;
            document.getElementById("outDist").innerText = distance;
    
            let stdTimeObj = getStandardTimeObj(distance, trackType, trackCond, classInfo, locName);
            document.getElementById("outStdTime").innerText = stdTimeObj.str;
    
            let halonMatch = text.match(/ハロンタイム\s*([\d\.\s-]+)/);
            if (halonMatch) raceSplits = halonMatch[1].split('-').map(x => parseFloat(x.trim())).filter(x => !isNaN(x));
    
            for(let i=0; i<lines.length; i++) {
                let line = lines[i].trim();
                if (!line) continue;
    
                let isCorner = line.match(/^(\d{1,2}\s+)+\d{1,2}$/); 
                let rankMatch = line.match(/^(\d{1,2})\s+(?:枠(\d)[^\s]*\s+)?(\d{1,2})\s*(.*)$/) || line.match(/^(\d{1,2})\s+([1-8])?\s*(\d{1,2})\s*(.*)$/);
    
                if (rankMatch && !isCorner && !line.includes("ハロンタイム") && !line.includes("払戻金") && !line.includes("着順") && !line.includes("コーナー")) {
                    let rVal = parseInt(rankMatch[1]);
                    if (rVal >= 1 && rVal <= 18) {
                        if (currentHorse && currentHorse.timeSec > 0) horses.push(currentHorse);
                        
                        let fVal = rankMatch[2] ? parseInt(rankMatch[2]) : null;
                        let nVal = parseInt(rankMatch[3]);
                        let rest = rankMatch[4].trim();
    
                        let nameVal = "";
                        if (rest === "") { 
                            if (i+1 < lines.length) { nameVal = lines[i+1].trim().split(/\s+/)[0].replace(/ブリンカー着用.*/, ''); }
                        } else { nameVal = rest.split(/\s+/)[0].replace(/ブリンカー着用.*/, ''); }
    
                        currentHorse = {
                            rank: rVal, frame: fVal, number: nVal, name: nameVal,
                            timeStr: "-", timeSec: 0, margin: "-", corners: "",
                            f3: 0, weightStr: "-", weightDiff: 0, pop: 0, imageData: null, badgeStr: ""
                        };
                    }
                } 
                
                if (currentHorse) {
                    let timeReg = /(?:(\d{1,2}):)?(\d{2}\.\d)/g;
                    let tMatches = [...line.matchAll(timeReg)];
                    
                    if (tMatches.length > 0 && currentHorse.timeSec === 0) {
                        let colonMatch = tMatches.find(m => m[0].includes(":"));
                        let raceTimeMatch = null;
    
                        if (colonMatch) {
                            raceTimeMatch = colonMatch[0];
                        } else {
                            let possible = tMatches.map(m => m[0]).filter(t => !t.includes(":") && parseFloat(t) >= 50.0 && parseFloat(t) < 180.0);
                            if (possible.length > 0) { raceTimeMatch = possible[possible.length - 1]; }
                        }
    
                        if (raceTimeMatch) {
                            let tSec = parseTime(raceTimeMatch);
                            if (tSec >= 50.0) { 
                                currentHorse.timeStr = raceTimeMatch;
                                currentHorse.timeSec = tSec;
                                let afterTime = line.substring(line.indexOf(raceTimeMatch) + raceTimeMatch.length).trim();
                                if (afterTime) {
                                    let mParts = afterTime.split(/\s+/);
                                    if (mParts.length > 1 && mParts[1].includes('/')) { currentHorse.margin = mParts[0] + " " + mParts[1]; }
                                    else { currentHorse.margin = mParts[0]; }
                                }
                            }
                        }
                    }
    
                    let wMatch = line.match(/(\d{3})\s*\(([+-]?\d+)\)/);
                    if (wMatch && currentHorse.weightStr === "-") {
                        currentHorse.weightStr = wMatch[0];
                        currentHorse.weightDiff = parseInt(wMatch[2]);
                        let fM = line.match(/(\d{2}\.\d)\s+\d{3}/);
                        if (fM) currentHorse.f3 = parseFloat(fM[1]);
                    }
    
                    let popMatch = line.match(/\s+(\d{1,2})$/);
                    if (popMatch && (line.match(/\d\.\d/) || line.includes("(") || line.includes("kg") || line.includes("人気"))) {
                        currentHorse.pop = parseInt(popMatch[1]);
                    }
    
                    let cornerMatch = line.match(/^([1-4角\d\s-,-]+)$/);
                    if (cornerMatch && !line.includes(".")) {
                        currentHorse.corners = cornerMatch[1].replace(/\s+/g, ' ').trim();
                    }
                }
            }
            if (currentHorse && currentHorse.timeSec > 0) horses.push(currentHorse);
            if(horses.length === 0) { alert("馬のデータを正しく読み込めませんでした。テキストが全てコピーされているか確認してください。"); return; }
    
            let winTimeSec = horses.find(h => h.rank === 1)?.timeSec || 0;
            let winTimeStr = horses.find(h => h.rank === 1)?.timeStr || "-";
            document.getElementById("outWinTime").innerText = winTimeSec > 0 ? winTimeStr : "-";
    
            let top3PCI = 0; let validTop3 = 0;
            let minF3 = Math.min(...horses.filter(h=>h.f3>0).map(h => h.f3)) || 34.0;
    
            horses.forEach(h => {
                if (h.f3 === 0) h.f3 = minF3; 
                if (h.pop === 0) h.pop = h.rank;
                h.t_first = h.timeSec - h.f3;
                h.d_first = distance - 600;
                if (h.d_first > 0 && h.f3 > 0) {
                    let t_first_600 = h.t_first / (h.d_first / 600);
                    h.pci = (t_first_600 / h.f3) * 50;
                } else { h.pci = 50; }
    
                if (h.rank <= 3) { top3PCI += h.pci; validTop3++; }
                let posArr = h.corners.split(/\s+/).filter(x=>x).map(Number);
                h.avgPos = posArr.length > 0 ? posArr.reduce((a,b)=>a+b,0) / posArr.length : (horses.length / 2);
                h.posRatio = h.avgPos / horses.length; 
            });
    
            let rpci = validTop3 > 0 ? top3PCI / validTop3 : 50;
            
            let diff = winTimeSec > 0 ? (winTimeSec - stdTimeObj.sec) : 0;
            let paceStr = "";
            if (distance <= 1000) paceStr = "📏 直線・超短距離 (スピード勝負)";
            else if (rpci > 52.0) paceStr = "🐢 スローペース (後傾ラップ)";
            else if (rpci < 48.0) paceStr = "🔥 ハイペース (前傾ラップ)";
            else paceStr = "⚖️ ミドルペース (平均ラップ)";
    
            let levelStr = ""; let levelDesc = "";
            if (winTimeSec === 0) {
                levelStr = "ー"; levelDesc = "勝ち時計が取得できませんでした。";
            } else if (diff <= -1.0) {
                levelStr = "Sランク (超ハイレベル🚀)";
                levelDesc = `基準タイムより ${Math.abs(diff).toFixed(1)}秒 も速い極めて優秀な時計です。上のクラスでも即通用するレベルの高い一戦でした。`;
            } else if (diff < 0.0) {
                levelStr = "Aランク (ハイレベル🌟)";
                levelDesc = `基準タイムを ${Math.abs(diff).toFixed(1)}秒 上回る優秀な時計です。上位馬は次走も有力です。`;
            } else if (diff <= 1.0) {
                levelStr = "Bランク (平均レベル⚖️)";
                levelDesc = `基準タイムとほぼ同等の決着(差 ${diff>0?'+':''}${diff.toFixed(1)}秒)です。当該クラスの標準的なレースレベルです。`;
            } else {
                levelStr = "Cランク (低調レベル⚠️)";
                levelDesc = `基準タイムより ${diff.toFixed(1)}秒 遅い決着です。ペースが遅すぎたか、メンバー全体のレベルが低かった可能性があります。上位馬の次走の過信は禁物です。`;
            }
            document.getElementById("outPaceType").innerHTML = `${paceStr} <br><span style="font-size:18px; color:#475569;">${levelStr}</span>`;
            document.getElementById("outPaceDesc").innerText = levelDesc;
    
            // 【最終改修】100点が連発しないシビアなスコア計算
            let winnerScore = 80;
            if (diff <= -1.5) winnerScore += 12;
            else if (diff <= -1.0) winnerScore += 8;
            else if (diff <= -0.5) winnerScore += 4;
            else if (diff >= 1.0) winnerScore -= 5;
            
            let secondHorse = horses.find(x => x.rank === 2);
            let marginToSecond = secondHorse ? secondHorse.margin : "";
            if (marginToSecond.includes("大差")) winnerScore += 10;
            else {
                let lengthsToSecond = parseMarginToLengths(marginToSecond);
                if (lengthsToSecond >= 4) winnerScore += 8;
                else if (lengthsToSecond >= 2.5) winnerScore += 4;
            }
            if (winnerScore > 98 && diff > -1.5) winnerScore = 98; // 真の伝説級以外は100点ロック
    
            horses.forEach(h => {
                let score = 60;
                let diffFromWin = h.timeSec - winTimeSec;
                let myDiff = h.timeSec - stdTimeObj.sec;
                let paceBonus = 0;
    
                if (h.rank === 1) {
                    score = winnerScore;
                } else {
                    score = winnerScore - (diffFromWin * 25); 
    
                    if (h.f3 <= minF3 + 0.1 && h.f3 > 0) score += 6;
                    else if (h.f3 <= minF3 + 0.3 && h.f3 > 0) score += 3;
    
                    if (distance > 1000 && diffFromWin <= 1.0) {
                        if (rpci < 48.0 && h.posRatio <= 0.4) paceBonus = 5; 
                        else if (rpci > 52.0 && h.posRatio >= 0.6) paceBonus = 5; 
                    }
                    score += paceBonus;
                }
    
                if (h.pop > 0 && h.pop <= 3 && h.rank >= 10) score -= 5;
                
                // スコアを 60点 〜 100点 に制限
                h.score = Math.max(60, Math.min(100, Math.round(score)));
    
                let autoTarget = diffFromWin <= 0.8 && h.rank !== 1 && (
                    (h.rank >= 4 && h.rank <= 9 && h.score >= 75) || 
                    (paceBonus >= 5 && h.rank >= 2 && h.rank <= 6) || 
                    (myDiff <= -1.0 && h.rank >= 2 && h.rank <= 5) 
                );
    
                h.badgeStr = "";
                if (h.score >= 98 && diff <= -1.0) h.badgeStr = "🔥激アツ";
                else if (autoTarget) h.badgeStr = "🎯次走注目";
    
                let memo = "";
                if (h.score >= 98) { 
                    memo = "歴史的なパフォーマンス!時計・上がり・展開すべてが規格外。次走も文句なしの激アツ。"; 
                } else if (autoTarget) {
                    if (paceBonus >= 5) memo = rpci < 48.0 ? "厳しいハイペースを先行して粘る極めて強い内容。次走ペースが落ち着けば確勝級。" : "前残りの絶望的な展開から猛追。展開不向きの中での好走で次走は絶好の狙い目。";
                    else memo = "着順以上に中身の濃いレース。自身の走破時計も優秀で次走の巻き返しに期待大。";
                } else if (h.rank === 1) {
                    if (h.score >= 80) memo = "優秀な時計での完勝。上のクラスでも即通用するポテンシャルを示した。";
                    else if (myDiff > 1.0) memo = "勝ちはしたが全体時計は平凡。次走昇級でのペースアップに対応できるかが鍵。";
                    else memo = "展開の利を活かした勝利。上手く抜け出しての堅実な走り。";
                } else if (h.rank <= 3) {
                    let isF3Fast = (h.f3 <= minF3 + 0.3 && h.f3 > 0);
                    if (isF3Fast) memo = "鋭い末脚で上位に食い込んだ。展開次第で勝ち負けになる。";
                    else if (myDiff <= 0.5) memo = "勝ち馬には離されたが、自身の時計も悪くない。クラス上位の力はある。";
                    else memo = "上位には入ったが時計的な価値は平凡。次走はメンバーレベルに注意。";
                } else if (h.rank <= 8) {
                    let isF3Fast = (h.f3 <= minF3 + 0.3 && h.f3 > 0);
                    if (h.pop > 0 && h.pop <= 3) memo = "上位人気に推されたが馬券圏外。次走での巻き返しに期待。";
                    else if (isF3Fast) memo = "後方から良い脚で追い上げている。展開がハマれば上位争いも。";
                    else if (h.posRatio <= 0.3 && distance > 1000) memo = "前寄りで粘り込みを図ったが最後は甘くなった。ペース次第で前進も。";
                    else if (Math.abs(h.weightDiff) >= 10) memo = `馬体重の大幅増減(${h.weightDiff > 0 ? '+' : ''}${h.weightDiff}kg)が影響した可能性も。状態が戻れば。`;
                    else memo = "中団からの雪崩れ込み。もうワンパンチ欲しい内容で、次走も展開の助けが必要。";
                } else {
                    let isF3Fast = (h.f3 <= minF3 + 0.3 && h.f3 > 0);
                    if (isF3Fast) memo = "大敗したが、上がりタイムは上位。後方から展開が全く向かなかった。";
                    else if (h.pop > 0 && h.pop <= 4) memo = "人気を大きく裏切る大敗。見えない疲れや不利があったか、立て直しが必要。";
                    else if (h.posRatio <= 0.3 && distance > 1000) memo = "果敢に先行したが直線で失速。息の入るペースになれば変わる余地も。";
                    else if (Math.abs(h.weightDiff) >= 10) memo = `大幅な馬体重変動(${h.weightDiff > 0 ? '+' : ''}${h.weightDiff}kg)も響いたか。馬体回復が急務。`;
                    else memo = "見せ場を作れず後方のまま入線。現状ではクラスの壁や力不足を感じる。";
                }
                h.memo = memo;
            });
    
            let incSection = document.getElementById("incidentsSection");
            if (incidents.length > 0) {
                let ul = document.getElementById("incidentsList");
                ul.innerHTML = "";
                incidents.forEach(inc => { let li = document.createElement("li"); li.innerText = inc; ul.appendChild(li); });
                incSection.style.display = "block";
            } else { incSection.style.display = "none"; }
    
            currentAnalysisData = { 
                raceInfo: finalRaceInfoStr, dist: distance, winTime: winTimeSec > 0 ? winTimeStr : "-", 
                stdTime: stdTimeObj.str, paceType: paceStr, levelStr: levelStr, levelDesc: levelDesc, 
                incidents: incidents, allHorses: horses 
            };
    
            if (raceSplits.length > 0) {
                let halfDist = distance / 2; let firstHalfTime = 0, secondHalfTime = 0;
                let dArr = []; let firstD = distance % 200 === 0 ? 200 : distance % 200;
                let tempDist = distance; dArr.push(firstD); tempDist -= firstD;
                while(tempDist > 0 && dArr.length < raceSplits.length) { dArr.push(200); tempDist -= 200; }
    
                let cumDist = 0; let cumTime = 0; let totalRaceTime = raceSplits.reduce((a,b)=>a+b, 0);
                for(let i=0; i<raceSplits.length; i++) {
                    if (cumDist + dArr[i] >= halfDist) {
                        let rem = halfDist - cumDist; firstHalfTime = cumTime + raceSplits[i] * (rem / dArr[i]); break;
                    }
                    cumDist += dArr[i]; cumTime += raceSplits[i];
                }
                secondHalfTime = totalRaceTime - firstHalfTime;
    
                document.getElementById("halfDistText1").innerText = halfDist;
                document.getElementById("halfDistText2").innerText = halfDist;
                document.getElementById("firstHalfTime").innerHTML = `${firstHalfTime.toFixed(1)}<span>秒</span>`;
                document.getElementById("secondHalfTime").innerHTML = `${secondHalfTime.toFixed(1)}<span>秒</span>`;
                document.getElementById("halvesComparison").style.display = "flex";
    
                let labels = []; let cur = 0;
                for (let i=0; i<raceSplits.length; i++) { cur += dArr[i] || 200; labels.push(cur + 'm'); }
    
                let minSplit = Math.min(...raceSplits);
                let pointBgColors = raceSplits.map(val => val === minSplit ? '#dc2626' : '#1e293b'); 
                let pointBorderColors = raceSplits.map(val => val === minSplit ? '#dc2626' : '#ffffff');
                let pointRadii = raceSplits.map(val => val === minSplit ? 8 : 5); 
                let pointHoverRadii = raceSplits.map(val => val === minSplit ? 10 : 7);
    
                if(paceChartInstance) paceChartInstance.destroy();
                const ctx = document.getElementById('paceChart').getContext('2d');
                paceChartInstance = new Chart(ctx, {
                    type: 'line', 
                    data: {
                        labels: labels,
                        datasets: [{
                            label: 'ハロンタイム (秒)', data: raceSplits, borderColor: '#3b82f6', backgroundColor: 'rgba(59, 130, 246, 0.15)',
                            borderWidth: 3, pointBackgroundColor: pointBgColors, pointBorderColor: pointBorderColors,
                            pointBorderWidth: 2, pointRadius: pointRadii, pointHoverRadius: pointHoverRadii, fill: true, tension: 0.1
                        }]
                    },
                    options: {
                        responsive: true, maintainAspectRatio: false,
                        scales: { y: { reverse: true, min: Math.floor(Math.min(...raceSplits)) - 0.5, max: Math.ceil(Math.max(...raceSplits)) + 0.5, title: { display: true, text: 'タイム (秒) ※上が速い', color: '#64748b', font: { size: 11 } } } },
                        plugins: { legend: { display: false }, tooltip: { callbacks: { label: function(context) { return context.parsed.y + (context.parsed.y === minSplit ? ' 秒 (最速ラップ🔥)' : ' 秒'); } } } }
                    }
                });
                document.getElementById("chartWrapper").style.display = "block";
            } else {
                document.getElementById("halvesComparison").style.display = "none"; document.getElementById("chartWrapper").style.display = "none";
            }
    
            renderMarginVisualizer(horses, text, trackType);
            parseAndRenderPayouts(lines);
    
            let tbody = document.querySelector("#resultTable tbody");
            tbody.innerHTML = "";
    
            horses.sort((a,b) => a.rank - b.rank).forEach(h => {
                let scoreClass = h.score >= 80 ? "score-high" : (h.score >= 70 ? "score-mid" : "score-low");
                if (h.score >= 95) scoreClass = "score-legend"; 
    
                let popDisplay = h.pop ? h.pop : "-";
                if(h.pop > 0) {
                    if(h.rank < h.pop) popDisplay = `<span class="pop-good">${h.pop}人気<br><small>(▲)</small></span>`;
                    else if (h.rank > h.pop) popDisplay = `<span class="pop-bad">${h.pop}人気<br><small>(▼)</small></span>`;
                    else popDisplay = `${h.pop}人気<br><small>(-)</small>`;
                }
    
                let badgeSelectHTML = `
                    <select class="badge-select" onchange="updateBadge(this, ${h.number})" style="margin-top:4px;">
                        <option value="" ${h.badgeStr === "" ? "selected" : ""}>-- バッジなし --</option>
                        <option value="🎯次走注目" ${h.badgeStr === "🎯次走注目" ? "selected" : ""}>🎯次走注目</option>
                        <option value="🔥激アツ" ${h.badgeStr === "🔥激アツ" ? "selected" : ""}>🔥激アツ</option>
                        <option value="⚠️危険な人気馬" ${h.badgeStr === "⚠️危険な人気馬" ? "selected" : ""}>⚠️危険な人気馬</option>
                        <option value="🐎大穴狙い" ${h.badgeStr === "🐎大穴狙い" ? "selected" : ""}>🐎大穴狙い</option>
                    </select>
                `;
    
                let tr = document.createElement("tr");
                tr.innerHTML = `
                    <td>${h.rank}</td>
                    <td>${h.number}</td>
                    <td style="text-align:left; font-weight:bold;">${h.name}</td>
                    <td>${h.margin}</td>
                    <td>${h.timeStr}</td>
                    <td>${h.f3 > 0 ? h.f3.toFixed(1) : '-'}</td>
                    <td>${h.corners}</td>
                    <td>${h.weightStr}</td>
                    <td>${popDisplay}</td>
                    <td>
                        <input type="number" class="score-input ${scoreClass}" data-number="${h.number}" value="${h.score}" onblur="handleScoreInput(this, ${h.number})" onchange="handleScoreInput(this, ${h.number})" title="点数を直接編集できます">
                    </td>
                    <td class="memo-cell">
                        <div class="memo-controls" style="margin-bottom:6px;">
                            ${badgeSelectHTML}
                            <button class="mic-btn" onclick="startDictation(this, ${h.number})" title="音声入力 (Chrome等対応ブラウザのみ)">🎙️</button>
                        </div>
                        <div contenteditable="true" class="editable-memo" data-number="${h.number}" onblur="handleMemoInput(this, ${h.number})">${h.memo}</div>
                    </td>
                    <td class="image-cell" data-html2canvas-ignore="false">
                        <input type="file" id="img-input-${h.number}" accept="image/*" style="display: none;" onchange="previewImage(this, ${h.number})">
                        <div id="img-preview-container-${h.number}">
                            ${h.imageData ? `<img src="${h.imageData}" class="img-preview" onclick="removeImage(${h.number})" title="クリックで削除">` : ''}
                        </div>
                        <button class="img-upload-btn" data-html2canvas-ignore="true" style="${h.imageData ? 'margin-top:4px; font-size:10px;' : ''}" onclick="document.getElementById('img-input-${h.number}').click()">
                            ${h.imageData ? '🔄 画像変更' : '📸 3走前画像'}
                        </button>
                    </td>
                `;
                tbody.appendChild(tr);
            });
    
            updateTopMemoDisplay();
    
            document.getElementById("resultSection").style.display = "block";
            setTimeout(() => { document.getElementById("resultSection").scrollIntoView({ behavior: 'smooth', block: 'start' }); }, 100);
        }
    
        function downloadPDF() {
            const element = document.getElementById('pdfContentArea');
            const opt = { margin: 10, filename: 'race_analysis_report.pdf', image: { type: 'jpeg', quality: 0.98 }, html2canvas: { scale: 2, useCORS: true, logging: false }, jsPDF: { unit: 'mm', format: 'a4', orientation: 'landscape' } };
            const btn = document.querySelector('.btn-pdf'); const originalText = btn.innerText; btn.innerText = "生成中...";
            html2pdf().set(opt).from(element).save().then(() => { btn.innerText = originalText; });
        }
    
        function copySummaryText() {
            if (!currentAnalysisData.raceInfo) return;
            let d = currentAnalysisData;
            
            let incidentsText = d.incidents.length > 0 ? `\n⚠️ 競走中の出来事・制裁等\n・` + d.incidents.join("\n・") + "\n" : "";
            
            let text = `【レース展開分析】\n🏇 ${d.raceInfo} (${d.dist}m)\n⏱️ 勝ち時計: ${d.winTime} (基準: ${d.stdTime})\n`;
            text += `📊 評価: ${d.paceType.replace(/<[^>]*>?/gm, ' ')} / ${d.levelStr.replace(/<[^>]*>?/gm, ' ')}\n`;
            text += `📝 タイムレベル詳細: ${d.levelDesc}\n`;
            text += incidentsText;
            
            text += `\n👑 上位・次走狙い馬メモ\n`;
            let summaryTargets = d.allHorses.filter(h => h.badgeStr !== "" || h.rank === 1).sort((a,b) => a.rank - b.rank);
            summaryTargets.forEach(h => {
                let memoDiv = document.querySelector(`.editable-memo[data-number='${h.number}']`);
                let currentMemo = memoDiv ? memoDiv.innerText : h.memo;
                let badge = h.badgeStr ? h.badgeStr : "";
                text += `${h.rank}着 ${h.name} [${h.score}点] ${badge}\n  ${currentMemo}\n\n`; 
            });
    
            text += `\n🐴 全頭評価メモ (保存用)\n`;
            d.allHorses.sort((a,b) => a.rank - b.rank).forEach(h => {
                let memoDiv = document.querySelector(`.editable-memo[data-number='${h.number}']`);
                let currentMemo = memoDiv ? memoDiv.innerText : h.memo;
                let badge = h.badgeStr ? h.badgeStr : "";
                text += `${h.rank}着 ${h.name} [${h.score}点] ${badge}\n  ${currentMemo}\n`;
            });
            
            navigator.clipboard.writeText(text).then(() => {
                const btn = document.querySelector('.btn-copy'); const originalText = btn.innerText; btn.innerText = "✅ コピー完了!";
                setTimeout(() => { btn.innerText = originalText; }, 2000);
            }).catch(err => { alert('クリップボードへのコピーに失敗しました。'); });
        }
    </script>
    </body>
    </html>


     
     
    統計データを使って競馬で勝ちたい🔥 回収率ブチ上げ隊長! ご期待ください🐎

    あなたへのおすすめ