// Template-overlay cert renderer.
// Each achievement type picks a baked JPG template; six overlay boxes
// inject user-input content at exact percentage coordinates that match
// the empty white regions of the template.
//
// Exposes window.CertPreview (replaces the legacy CSS-rendered cert).

(function () {
  const TEMPLATES = {
    'hole-in-one':   '../templates/hole-in-one.jpg?v=5',
    'birdie':        '../templates/birdie.jpg?v=6',
    'eagle':         '../templates/eagle.jpg?v=6',
    'albatross':     '../templates/albatross.jpg?v=6',
    'disaster-hole': '../templates/disaster-hole.jpg?v=6',
  };

  function templateKey(type) {
    const t = (type || '').toLowerCase().trim();
    if (t.includes('hole in one') || t.includes('ace')) return 'hole-in-one';
    if (t.includes('albatross') || t.includes('double eagle')) return 'albatross';
    if (t.includes('eagle')) return 'eagle';
    if (t.includes('birdie')) return 'birdie';
    if (t.includes('catastrophic') || t.includes('disaster') || t.includes('shank') ||
        t.includes('splash') || t.includes('meltdown') || t.includes('hell')) return 'disaster-hole';
    return 'hole-in-one';
  }

  function magicLabel(type) {
    const t = (type || '').toLowerCase().trim();
    if (t.includes('hole in one') || t.includes('ace')) return 'ACE!';
    if (t.includes('albatross') || t.includes('double eagle')) return 'ALBATROSS!';
    if (t.includes('eagle')) return 'EAGLE!';
    if (t.includes('birdie')) return 'BIRDIE!';
    if (t.includes('catastrophic')) return '12!';
    if (t.includes('shank')) return 'SHANK!';
    if (t.includes('splash')) return 'SPLASH!';
    if (t.includes('meltdown')) return 'MELTDOWN!';
    if (t.includes('hell')) return 'HELL!';
    if (t.includes('disaster')) return 'DISASTER!';
    return 'ACE!';
  }

  const DEFAULT_PAR = [4,4,3,4,5,3,4,4,4, 4,5,3,4,4,4,4,3,5];

  function formatDate(s) {
    if (!s) return '';
    const d = new Date(s + (s.length === 10 ? 'T12:00:00' : ''));
    if (isNaN(d.getTime())) return s;
    const months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
    return `${months[d.getMonth()]} ${d.getDate()}, ${d.getFullYear()}`;
  }

  const SERIF = "'Playfair Display', Georgia, serif";
  const SANS  = "Inter, system-ui, sans-serif";

  // Template box bounds (X1, Y1, X2, Y2 in % of container). The four data
  // squares + photo were hand-aligned to the gold frame openings via the
  // interactive aligner tool.
  const DEFAULT_BOXES = {
    dateBand:   { x1: 33.27, y1: 26.23, x2: 68.38, y2: 29.41 },   // matched to template frame opening
    nameInfo:   { x1: 5.47, y1: 31.29, x2: 35.85, y2: 47.71 },
    holeStats:  { x1: 5.44, y1: 53.98, x2: 36.52, y2: 70.15 },
    photo:      { x1: 42.25, y1: 31.80, x2: 73.84, y2: 72.21 },
    holeLayout: { x1: 77.32, y1: 31.51, x2: 94.54, y2: 72.52 },
    scorecard:  { x1: 5.43, y1: 76.58, x2: 58.47, y2: 90.84 },
    witnessName:{ x1: 66.30, y1: 76.19, x2: 81.90, y2: 80.89 },   // sits just above the baked "WITNESS" line, clear of the label
  };

  // Helper: convert (X1,Y1,X2,Y2) box into CSS positioning.
  const boxStyle = (b, extra = {}) => ({
    position: 'absolute',
    left:   `${b.x1}%`,
    top:    `${b.y1}%`,
    width:  `${b.x2 - b.x1}%`,
    height: `${b.y2 - b.y1}%`,
    background: '#FAF4E4',
    overflow: 'hidden',
    borderRadius: '0.5cqw',
    ...extra,
  });

  const Watermark = () => (
    <svg style={{
      position:'absolute', inset:0, width:'100%', height:'100%',
      pointerEvents:'none', zIndex: 50,
    }} preserveAspectRatio="none">
      <defs>
        <pattern id="ct-wm" x="0" y="0" width="540" height="180"
          patternUnits="userSpaceOnUse" patternTransform="rotate(-30)">
          <text x="0" y="60" fill="#A38137" fillOpacity="0.20"
            fontFamily="Inter, system-ui, sans-serif" fontWeight="700"
            fontSize="34" letterSpacing="9">
            PREVIEW · UNFORGETTABLEGOLFHOLES.COM ·
          </text>
        </pattern>
      </defs>
      <rect width="100%" height="100%" fill="url(#ct-wm)" />
    </svg>
  );

  function StatCell({ val, label, title, fill, pdfMode, scoreTop, scoreLeft }) {
    const liftLocal = (sz, mult = 0.22) => pdfMode
      ? `translateY(-${(sz * mult).toFixed(3)}cqw)`
      : '';
    return (
      <div id={fill ? 'cert-score-cell' : undefined} style={{
        background: fill ? '#1F5240' : '#FFFFFF',
        border: `0.12cqw solid ${fill ? '#A38137' : '#A38137aa'}`,
        borderRadius: '0.25cqw',
        position: 'relative',
        minHeight: 0,
      }}>
        <div style={{
          position:'absolute', top:'0.3cqw', right:'0.5cqw',
          fontFamily: SANS,
          fontSize:'0.6cqw', fontWeight:600,
          letterSpacing:'0.08cqw', textTransform:'uppercase',
          color: fill ? '#A38137' : '#4E544F',
          opacity: 0.85,
          transform: liftLocal(0.6),
        }}>{title}</div>
        <div style={{
          position:'absolute',
          // Fill (Score) cell carries the EAGLE! label below, so lift its big
          // number up to sit midway between the cell top and that label.
          top: fill ? (scoreTop || '20%') : '44%',
          left: fill ? (scoreLeft || '50%') : 0,
          right: fill ? 'auto' : 0,
          textAlign:'center',
          transform: fill
            ? 'translate(-50%, -50%)'
            : (pdfMode
                ? `translateY(calc(-50% - ${(2.2 * 0.36).toFixed(3)}cqw))`
                : 'translateY(-50%)'),
          fontFamily: SERIF,
          fontSize: fill ? '3.0cqw' : '2.2cqw', fontWeight:700,
          color: fill ? '#F0D283' : '#1F5240',
          lineHeight:1,
          whiteSpace:'nowrap',
        }}>{val}</div>
        {label && (
          <div style={{
            position:'absolute', bottom:'0.25cqw', left:0, right:0,
            textAlign:'center',
            fontFamily: SANS,
            fontSize:'0.65cqw', fontWeight:700,
            letterSpacing:'0.1cqw',
            color: '#A38137',
            transform: liftLocal(0.65),
          }}>{label}</div>
        )}
      </div>
    );
  }

  function Scorecard({ par, score, parOut, parIn, parTot, scOut, scIn, scTot, featuredHole, pdfMode }) {
    const liftSc = pdfMode ? `translateY(-${(0.95 * 0.22).toFixed(3)}cqw)` : 'none';
    // Multi-tonal palette — each row + total cells get a distinct fill.
    // (Lighter tones across the board for a softer look.)
    const HEADER_BG = '#3D6B58';   // lighter dark green — Hole header row
    const PAR_BG    = '#7DA396';   // lighter medium green — Par row
    const SCORE_BG  = '#CFE0D6';   // lighter sage — Score row
    const TOTAL_BG  = '#C09F58';   // lighter gold — Out / In / Tot column
    const ACE_BG    = '#E5C485';   // soft bright gold — featured hole
    const LABEL_BG  = '#2D5345';   // lighter deepest green — row labels
    const CREAM     = '#FAF4E4';
    const INK       = '#1F2420';

    const baseCell = {
      display:'flex', alignItems:'center', justifyContent:'center',
      borderRadius: '0.2cqw',
      fontFamily: SANS,
      fontSize: '0.95cqw', fontWeight: 700,
      letterSpacing: '0.04cqw',
      lineHeight: 1,
      textAlign: 'center',
      transform: liftSc,
    };

    const cell = (bg, fg, opts = {}) => ({
      ...baseCell,
      background: bg,
      color: fg,
      ...opts,
    });

    // 22 columns: label | 1–9 | Out | 10–18 | In | Tot
    const cols = '0.85fr ' + 'repeat(9, 1fr) '.repeat(1) + '1.1fr ' + 'repeat(9, 1fr) '.repeat(1) + '1.1fr 1.15fr';

    const renderRow = (label, values, out, ins, tot, rowBg, scoreRow = false) => (
      <>
        <div style={cell(LABEL_BG, CREAM, {
          fontSize:'0.8cqw', textTransform:'uppercase', letterSpacing:'0.15cqw',
        })}>{label}</div>
        {values.slice(0,9).map((v, i) => {
          const isAce = scoreRow && (i + 1) === featuredHole;
          return (
            <div key={`a-${i}`} style={cell(
              isAce ? ACE_BG : rowBg,
              isAce ? INK   : (rowBg === SCORE_BG ? INK : CREAM),
              isAce ? { boxShadow: '0 0 0 0.06cqw #A38137' } : {},
            )}>{v}</div>
          );
        })}
        <div style={cell(TOTAL_BG, CREAM)}>{out}</div>
        {values.slice(9,18).map((v, i) => {
          const isAce = scoreRow && (i + 10) === featuredHole;
          return (
            <div key={`b-${i}`} style={cell(
              isAce ? ACE_BG : rowBg,
              isAce ? INK   : (rowBg === SCORE_BG ? INK : CREAM),
              isAce ? { boxShadow: '0 0 0 0.06cqw #A38137' } : {},
            )}>{v}</div>
          );
        })}
        <div style={cell(TOTAL_BG, CREAM)}>{ins}</div>
        <div style={cell(TOTAL_BG, CREAM)}>{tot}</div>
      </>
    );

    return (
      <div style={{
        display:'grid',
        gridTemplateColumns: cols,
        gridTemplateRows: '1fr 1fr 1fr',
        gap:'0.18cqw',
        height:'100%',
      }}>
        {/* Header row */}
        <div style={cell(LABEL_BG, CREAM, {
          fontSize:'0.8cqw', textTransform:'uppercase', letterSpacing:'0.15cqw',
        })}>Hole</div>
        {[1,2,3,4,5,6,7,8,9].map(h => (
          <div key={`h-${h}`} style={cell(HEADER_BG, CREAM)}>{h}</div>
        ))}
        <div style={cell(TOTAL_BG, CREAM, {
          fontSize:'0.8cqw', textTransform:'uppercase', letterSpacing:'0.12cqw',
        })}>Out</div>
        {[10,11,12,13,14,15,16,17,18].map(h => (
          <div key={`h-${h}`} style={cell(HEADER_BG, CREAM)}>{h}</div>
        ))}
        <div style={cell(TOTAL_BG, CREAM, {
          fontSize:'0.8cqw', textTransform:'uppercase', letterSpacing:'0.12cqw',
        })}>In</div>
        <div style={cell(TOTAL_BG, CREAM, {
          fontSize:'0.8cqw', textTransform:'uppercase', letterSpacing:'0.12cqw',
        })}>Tot</div>

        {/* Par row */}
        {renderRow('Par',   par,   parOut, parIn, parTot, PAR_BG)}
        {/* Score row */}
        {renderRow('Score', score, scOut,  scIn,  scTot,  SCORE_BG, true)}
      </div>
    );
  }

  // Single-line text that shrinks its font-size (down to minCqw) until it fits
  // the width of its parent — used for the date · course band, where long
  // course names would otherwise overflow and clip.
  function FitText({ text, maxCqw, minCqw, baseStyle }) {
    const ref = React.useRef(null);
    React.useLayoutEffect(() => {
      const el = ref.current;
      if (!el || !el.parentElement) return;
      const avail = el.parentElement.clientWidth - 6;   // breathing room off the border
      if (avail <= 0) return;
      let size = maxCqw;
      el.style.fontSize = size + 'cqw';
      let guard = 0;
      while (el.scrollWidth > avail && size > minCqw && guard < 80) {
        size -= 0.04;
        el.style.fontSize = size + 'cqw';
        guard++;
      }
    }, [text, maxCqw, minCqw]);
    return <div ref={ref} style={{ ...baseStyle, fontSize: maxCqw + 'cqw' }}>{text}</div>;
  }

  function CertTemplate({ fields = {}, holePng, photoPng, scoreData, watermark = true, pdfMode = false, pdfStretch = false, templateSrc = null, boxes = null, scoreTop = '34.5%', scoreLeft = '50%' }) {
    const BOXES = boxes || DEFAULT_BOXES;   // `boxes` override is used by the live aligner tool
    const tk = templateKey(fields.achievementType);
    const src = templateSrc || TEMPLATES[tk];

    // html2canvas snapshots text glyphs slightly lower than the browser renders
    // them; lift each line by ~22% of its font size when generating the PDF.
    const lift = (fontSizeCqw, mult = 0.22) => pdfMode
      ? `translateY(-${(fontSizeCqw * mult).toFixed(3)}cqw)`
      : 'none';

    const golferName = fields.golferName || 'Your Name';
    const courseName = fields.courseName || 'Course Name';
    const dateText   = formatDate(fields.achievementDate) || 'Date of Achievement';
    const featuredHole = parseInt(fields.holeNumber || '1', 10) || 1;
    const par   = scoreData?.par   || DEFAULT_PAR;
    const score = scoreData?.score || DEFAULT_PAR.map((p, i) => i === featuredHole - 1 ? 1 : p);
    const featuredScore = parseInt(score[featuredHole - 1], 10) || 1;

    const sumRange = (arr, a, b) => arr.slice(a, b).reduce((s,v) => s + (parseInt(v) || 0), 0);
    const parOut = sumRange(par, 0, 9),   parIn = sumRange(par, 9, 18),   parTot = parOut + parIn;
    const scOut  = sumRange(score, 0, 9), scIn  = sumRange(score, 9, 18), scTot  = scOut + scIn;

    return (
      <div style={{
        position: 'relative', width: '100%', height: '100%',
        // 4:3 to match the printed cert (16x12in) exactly. The print renders
        // THIS component at 4800x3600 (4:3), so the preview must be 4:3 too —
        // then preview and print are pixel-identical.
        aspectRatio: '4 / 3',
        containerType: 'inline-size',
        background: pdfMode ? 'transparent' : '#1F5240',
        boxShadow: pdfMode ? 'none' : '0 8px 32px rgba(0,0,0,0.18), 0 2px 6px rgba(0,0,0,0.08)',
      }}>
        {/* Base template image */}
        <img src={src} alt="" style={{
          position:'absolute', inset:0,
          width:'100%', height:'100%', display:'block', objectFit:'cover',
        }} />

        {/* BOX 1 — Date + Course band (gold-framed); text auto-fits the width */}
        <div style={boxStyle(BOXES.dateBand, {
          display:'flex', alignItems:'center', justifyContent:'center',
          border: '0.18cqw solid #A38137',
          boxShadow: 'inset 0 0 0 0.04cqw #A38137aa',
          borderRadius: '0.25cqw',
        })}>
          <FitText
            text={`${dateText.toUpperCase()} · ${courseName.toUpperCase()}`}
            maxCqw={1.7}
            minCqw={0.85}
            baseStyle={{
              fontFamily: SANS,
              fontWeight: 700,
              letterSpacing: '0.13em',   // em so it scales as the text shrinks
              color: '#1F5240',
              textTransform: 'uppercase',
              textAlign: 'center',
              whiteSpace: 'nowrap',
              transform: lift(1.7, 0.40),
            }}
          />
        </div>

        {/* BOX 2 — Achieved By + Name + Club/Hole/Distance */}
        <div style={boxStyle(BOXES.nameInfo, { padding:'1.2cqw 1.4cqw' })}>
          <div style={{
            fontFamily: SANS,
            fontSize: '0.95cqw', fontWeight: 600,
            letterSpacing: '0.2cqw',
            color: '#4E544F',
            textTransform: 'uppercase',
            transform: lift(0.95),
          }}>Achieved by</div>
          <div style={{
            fontFamily: SERIF,
            fontSize: '2.6cqw', fontWeight: 700,
            color: '#1F5240',
            marginTop: '0.35cqw', lineHeight: 1.1,
            transform: lift(2.6),
          }}>{golferName}</div>
          <div style={{
            height: '0.1cqw', background: '#A38137', opacity: 0.7,
            margin: '0.45cqw 0 0.55cqw',
          }} />
          <div style={{
            display:'flex', flexDirection:'column', gap:'0.42cqw',
          }}>
            {[
              ['Club',     fields.clubUsed || 'Driver'],
              ['Hole',     fields.holeNumber || '—'],
              ['Distance', fields.yardage ? `${fields.yardage} ${fields.distanceUnit === 'm' ? 'meters' : 'yards'}` : '—'],
            ].map(([k, v]) => (
              <div key={k} style={{
                display:'flex', alignItems:'baseline', justifyContent:'space-between',
                gap:'1cqw',
                borderBottom: '0.05cqw dotted rgba(163,129,55,0.45)',
                paddingBottom: '0.25cqw',
              }}>
                <span style={{
                  fontFamily: SANS,
                  fontSize: '0.95cqw', fontWeight: 700,
                  letterSpacing: '0.18cqw',
                  textTransform: 'uppercase',
                  color: '#4E544F',
                  display: 'inline-block',
                  transform: lift(0.95),
                }}>{k}</span>
                <span style={{
                  fontFamily: SANS,
                  fontSize: '1.55cqw', fontWeight: 800,
                  color: '#1F2420',
                  lineHeight: 1,
                  letterSpacing: '0.02cqw',
                  display: 'inline-block',
                  transform: lift(1.55),
                }}>{v}</span>
              </div>
            ))}
          </div>
        </div>

        {/* BOX 3 — Hole Statistics (2×2 grid) */}
        <div style={boxStyle(BOXES.holeStats, {
          padding: '1cqw 1.1cqw',
          display: 'flex', flexDirection: 'column',
        })}>
          <div style={{
            fontFamily: SANS,
            fontSize: '0.95cqw', fontWeight: 600,
            letterSpacing: '0.18cqw',
            color: '#4E544F',
            textTransform: 'uppercase',
            textAlign: 'center',
            marginBottom: '0.8cqw',
            transform: lift(0.95),
          }}>Hole Statistics</div>
          <div style={{
            flex: 1,
            display: 'grid',
            gridTemplateColumns: '1fr 1fr',
            gridTemplateRows: '1fr 1fr',
            gap: '0.5cqw',
            minHeight: 0,
          }}>
            <StatCell val={fields.holeNumber || '—'} title="Hole"     fill={false} pdfMode={pdfMode} />
            <StatCell val={fields.par || '—'}        title="Par"      fill={false} pdfMode={pdfMode} />
            <StatCell val={fields.yardage || '—'}    title="Distance" fill={false} pdfMode={pdfMode} />
            <StatCell val={featuredScore} title="Score" label={magicLabel(fields.achievementType)} fill={true} pdfMode={pdfMode} scoreTop={scoreTop} scoreLeft={scoreLeft} />
          </div>
        </div>

        {/* BOX 4 — Player Photo (square corners to match the template frame) */}
        <div style={boxStyle(BOXES.photo, {
          display:'flex', alignItems:'center', justifyContent:'center',
          background:'#E8DFC4',
          borderRadius: 0,
        })}>
          {photoPng
            ? <img src={photoPng} alt=""
                style={{ width:'100%', height:'100%', objectFit:'cover' }} />
            : <span style={{
                fontFamily: SERIF, fontSize:'2cqw', color:'#A8A399',
              }}>Photo</span>}
        </div>

        {/* BOX 5 — Course Layout (fills the entire box) */}
        <div style={boxStyle(BOXES.holeLayout, {
          display:'flex', alignItems:'center', justifyContent:'center',
          padding: 0,
        })}>
          {holePng
            ? <img src={holePng} alt=""
                style={{
                  width:'100%', height:'100%',
                  objectFit:'fill', display:'block',
                }} />
            : <span style={{
                fontFamily: SERIF, fontSize:'1.5cqw', color:'#A8A399',
              }}>Hole Layout</span>}
        </div>

        {/* BOX 6 — Scorecard */}
        <div style={boxStyle(BOXES.scorecard, { padding:'0.6cqw 0.8cqw' })}>
          <Scorecard
            par={par} score={score}
            parOut={parOut} parIn={parIn} parTot={parTot}
            scOut={scOut} scIn={scIn} scTot={scTot}
            featuredHole={featuredHole}
            pdfMode={pdfMode}
          />
        </div>

        {/* BOX 7 — Witness name (optional): auto-fits above the baked WITNESS line,
            in the player-name font + colour. */}
        {fields.witnessName && (
          <div style={{
            position:'absolute',
            left:   `${BOXES.witnessName.x1}%`,
            top:    `${BOXES.witnessName.y1}%`,
            width:  `${BOXES.witnessName.x2 - BOXES.witnessName.x1}%`,
            height: `${BOXES.witnessName.y2 - BOXES.witnessName.y1}%`,
            display:'flex', alignItems:'flex-end', justifyContent:'center',
          }}>
            <FitText
              text={fields.witnessName}
              maxCqw={1.7}
              minCqw={0.7}
              baseStyle={{
                fontFamily: SERIF,
                fontWeight: 700,
                color: '#1F5240',
                lineHeight: 1,
                whiteSpace: 'nowrap',
                textAlign: 'center',
                transform: lift(1.8),
              }}
            />
          </div>
        )}

        {watermark && <Watermark />}
      </div>
    );
  }

  window.CertPreview = CertTemplate;
})();
