<!DOCTYPE html>
<html lang="bn">
<head>
  <meta charset="UTF-8">
  <title>ফটোকার্ড জেনারেটর</title>
  <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@400;700&display=swap" rel="stylesheet">
  <script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
  <style>
    body{font-family:'Hind Siliguri',sans-serif;margin:0;padding:20px;background:linear-gradient(135deg,#f0f4f7,#d9e2ec)}
    h2{ text-align:center;margin-bottom:30px;font-size:30px;color:#2c3e50}
    .wrapper{display:flex;flex-wrap:wrap;justify-content:center;align-items:flex-start;gap:30px}
    .card-container{position:relative;width:800px;height:800px;border-radius:16px;overflow:hidden;box-shadow:0 8px 20px rgba(0,0,0,.15);background:#fff;flex-shrink:0}
    .bg-img{position:absolute;inset:0;width:100%;height:100%;object-fit:cover;z-index:0;display:none}
    .logo{position:absolute;top:20px;right:30px;width:120px;z-index:2}
    .main-image{position:absolute;top:90px;left:30px;width:740px;height:410px;object-fit:cover;border:6px solid #fff;border-top-right-radius:60px;border-bottom-left-radius:60px;border-top-left-radius:10px;border-bottom-right-radius:10px;box-shadow:0 8px 20px rgba(0,0,0,.4)}
    .headline{
      position:absolute; top:540px; left:50%; transform:translateX(-50%);
      width:90%;
      font-size:30px; line-height:1.4; font-weight:700; color:#000; text-align:center; z-index:3; user-select:text;
      /* লাইন ব্রেক স্মুথ করার জন্য */
      white-space:normal; word-break:break-word; overflow-wrap:anywhere;
      /* পারফর্মেন্স হিন্ট */
      will-change:width,font-size,left,top;
    }
    .headline:focus{outline:2px dashed #2c3e50;outline-offset:2px}
    .date{position:absolute;bottom:20px;left:30px;font-size:23px;font-weight:600;color:#000;z-index:3}
    .url{position:absolute;bottom:20px;right:30px;font-size:23px;font-weight:600;color:#000;z-index:3}

    .form-section{max-width:420px;background:#fff;padding:30px 40px 30px 30px;border-radius:12px;box-shadow:0 4px 12px rgba(0,0,0,.1);font-size:16px;flex:1;min-width:280px}
    .form-group{margin-bottom:20px;text-align:left}
    .form-group label{display:block;margin-bottom:6px;font-weight:600;color:#333;font-size:15px}
    .form-section input,.form-section textarea{width:100%;padding:12px;font-size:16px;border:1px solid #ccc;border-radius:8px;box-shadow:0 2px 6px rgba(0,0,0,.05);font-family:'Hind Siliguri',sans-serif}
    .form-section textarea{resize:vertical;min-height:80px}
    .form-section button{width:100%;padding:12px;font-size:16px;background:#2c3e50;color:#fff;border:none;border-radius:8px;cursor:pointer;transition:.3s;font-weight:bold}
    .form-section button:hover{background:#1a242f}

    @media (max-width:1020px){.wrapper{flex-direction:column;align-items:center}.card-container{transform:scale(.95)}}
    @media (max-width:600px){.card-container{transform:scale(.85)}.form-section{width:100%;padding:20px}}

    /* এডিট UI */
    .editor-handle{position:absolute;width:14px;height:14px;background:#fff;border:2px solid #2c3e50;border-radius:50%;z-index:10;box-shadow:0 2px 6px rgba(0,0,0,.15)}
    .editor-handle.move{cursor:grab}
    .editor-handle.move:active{cursor:grabbing}
    .editor-handle.resize{cursor:nwse-resize}
    .editor-toolbar{position:absolute;display:none;align-items:center;gap:6px;background:#fff;border:1px solid #e5e7eb;border-radius:10px;padding:6px;box-shadow:0 8px 20px rgba(0,0,0,.12);z-index:11}
    .editor-toolbar button{border:1px solid #e5e7eb;background:#fff;padding:6px 8px;border-radius:8px;font-weight:700;cursor:pointer}
    .editor-toolbar button:hover{background:#f3f4f6}
    .ui-ignore{pointer-events:auto}

    /* BG সিলেক্টর */
    .bg-selector{display:grid;grid-template-columns:repeat(3,1fr);gap:10px}
    .bg-option{position:relative;border-radius:10px;display:inline-block}
    .bg-option input{position:absolute;opacity:0;pointer-events:none}
    .bg-option img{width:100%;height:84px;object-fit:cover;border-radius:10px;border:2px solid transparent;box-shadow:0 2px 8px rgba(0,0,0,.08);cursor:pointer;transition:.2s;user-select:none}
    .bg-option:hover img{transform:translateY(-1px)}
    .bg-option input:checked + img{border-color:#2c3e50;box-shadow:0 4px 14px rgba(0,0,0,.18)}
  </style>
  <style>
  .hiddenn { display: none; } /* চাইলে visibility:hidden বা visually-hidden টেকনিকও ব্যবহার করতে পারেন */
</style>
</head>
<body>

  <h2>🌟 ফটোকার্ড জেনারেটর</h2>

  <div class="wrapper">
    <div id="card" class="card-container">
      <!-- 3টি BG -->
      <img id="bg1" class="bg-img" src="/pc/bg-2.png" crossorigin="anonymous">
      <img id="bg2" class="bg-img" src="/pc/bg-1.png" crossorigin="anonymous">
      <img id="bg3" class="bg-img" src="https://i.postimg.cc/fyLWQ5Rk/20final5.jpg" crossorigin="anonymous">

      <img id="logoImage" class="logo" src="/pc/Newsnest-logo-PNG-01.png" crossorigin="anonymous">
      <img id="mainImage" class="main-image" src="" crossorigin="anonymous">

      <!-- এডিটেবল হেডলাইন -->
      <div id="headlineText" class="headline" contenteditable="true" spellcheck="false">আপনার শিরোনাম যেখানে থাকবে</div>

      <div id="dateText" class="date"></div>
      <div id="urlText" class="url">news.techbari.com</div>

      <!-- এডিট UI (html2canvas ইগনোর) -->
      <div id="moveHandle" class="editor-handle move ui-ignore" title="Drag to move"></div>
      <div id="resizeHandle" class="editor-handle resize ui-ignore" title="Drag: ↑/↓ = font size, ←/→ = line breaks (width)"></div>

      <div id="editorToolbar" class="editor-toolbar ui-ignore">
        <button type="button" data-cmd="bold">B</button>
        <button type="button" data-cmd="italic"><i>I</i></button>
        <button type="button" data-cmd="underline"><u>U</u></button>
        <span style="width:6px;"></span>
        <button type="button" data-align="left">L</button>
        <button type="button" data-align="center">C</button>
        <button type="button" data-align="right">R</button>
      </div>
    </div>

    <div class="form-section">
      <div class="form-group">
        <label>🖼️ বিজি ইমেজ বাছাই করুন</label>
        <div class="bg-selector">
          <label class="bg-option">
            <input type="radio" name="bgSelect" value="bg1" checked>
            <img src="https://i.postimg.cc/fyLWQ5Rk/20final5.jpg" alt="BG 1" crossorigin="anonymous">
          </label>
          <label class="bg-option">
            <input type="radio" name="bgSelect" value="bg2">
            <img src="/pc/bg-1.png" alt="BG 2" crossorigin="anonymous">
          </label>
          <label class="bg-option">
            <input type="radio" name="bgSelect" value="bg3">
            <img src="/pc/bg-2.png" alt="BG 3" crossorigin="anonymous">
          </label>
        </div>
      </div>

      <div class="form-group hidden">
        <label for="mainImageInput">📸 মেইন ইমেজ (740px × 410px)</label>
        <input type="file" id="mainImageInput" accept="image/*">
      </div>

      <div class="form-group">
        <label for="headlineInput">📰 শিরোনাম</label>
        <textarea id="headlineInput" placeholder="শিরোনাম লিখুন"></textarea>
      </div>

      <div class="form-group">
        <label for="headlineFontSize">🔠 হেডলাইন ফন্ট সাইজ (px)</label>
        <input type="number" id="headlineFontSize" value="30" min="10" max="150">
      </div>

      <div class="form-group">
        <label for="headlineColor">🎨 হেডলাইন ফন্ট কালার</label>
        <input type="color" id="headlineColor" value="#ffffff">
      </div>

      <div class="form-group">
        <label for="dateInput">📅 তারিখ (আজকের তারিখ বসাতে ফাঁকা রাখুন)</label>
        <input type="text" id="dateInput" placeholder="">
      </div>

      <div class="form-group hidden">
        <label for="urlInput">🌐 ওয়েবসাইট</label>
        <input type="text" id="urlInput" placeholder="যেমন: trishal24.com">
      </div>

      <div class="form-group hidden">
        <label for="logoInput">🔖 লোগো ইমেজ (60px × 80px)</label>
        <input type="file" id="logoInput" accept="image/*">
      </div>

      <button onclick="generateCard()">Generate & Download</button>
    </div>
  </div>

  <script>
    /* === ফাইল ইনপুট === */
    const mainImageInput=document.getElementById('mainImageInput');
    const logoInput=document.getElementById('logoInput');

    mainImageInput.addEventListener('change', function(){
      const f=this.files[0]; if(!f) return;
      const r=new FileReader();
      r.onload=(e)=>{ document.getElementById('mainImage').src=e.target.result; };
      r.readAsDataURL(f);
    });

    logoInput.addEventListener('change', function(){
      const f=this.files[0]; if(!f) return;
      const r=new FileReader();
      r.onload=(e)=>{ document.getElementById('logoImage').src=e.target.result; };
      r.readAsDataURL(f);
    });

    /* === BG সিলেকশন === */
    const bgMap={ bg1:document.getElementById('bg1'), bg2:document.getElementById('bg2'), bg3:document.getElementById('bg3') };
    function setBackground(which){ Object.values(bgMap).forEach(i=>i.style.display='none'); if(bgMap[which]) bgMap[which].style.display='block'; }
    document.querySelectorAll('input[name="bgSelect"]').forEach(r => r.addEventListener('change',()=>setBackground(r.value)));

    /* === এক্সপোর্ট === */
    function generateCard(){
      document.getElementById('headlineInput').value=document.getElementById('headlineText').innerText;

      const headline=document.getElementById('headlineInput').value;
      const dateInput=document.getElementById('dateInput').value.trim();
      const url=document.getElementById('urlInput').value;

      const today=new Date();
      const defaultDate=today.toLocaleDateString('bn-BD',{day:'numeric',month:'long',year:'numeric'});
      const finalDate=dateInput!==''?dateInput:defaultDate;

      const fontSize=document.getElementById('headlineFontSize').value;
      const color=document.getElementById('headlineColor').value||'#000';

      const hl=document.getElementById('headlineText');
      hl.innerText=headline||'শিরোনাম দেওয়া হয়নি';
      hl.style.fontSize=fontSize+'px';
      hl.style.color=color;

      document.getElementById('dateText').innerText=finalDate;
      document.getElementById('urlText').innerText=url||'Trishal24.com';

      html2canvas(document.getElementById('card'),{
        useCORS:true,allowTaint:true,backgroundColor:null,
        ignoreElements:(el)=>el.classList&&el.classList.contains('ui-ignore')
      }).then(canvas=>{
        const a=document.createElement('a'); a.download='photocard.png'; a.href=canvas.toDataURL(); a.click();
      });
    }
  </script>

  <script>
    /* === লাইভ কন্ট্রোল === */
    document.getElementById('headlineFontSize').addEventListener('input',function(){
      document.getElementById('headlineText').style.fontSize=this.value+'px';
      updateEditorUI();
    });
    document.getElementById('headlineColor').addEventListener('input',function(){
      document.getElementById('headlineText').style.color=this.value;
    });
    document.getElementById('headlineInput').addEventListener('input',function(){
      document.getElementById('headlineText').innerText=this.value; updateEditorUI();
    });
    document.getElementById('headlineText').addEventListener('input',function(){
      document.getElementById('headlineInput').value=this.innerText; updateEditorUI();
    });
  </script>

  <!-- === ড্র্যাগ/রিসাইজ (X = width → line breaks, Y = font-size) স্মুথ rAF === -->
  <script>
    const card = document.getElementById('card');
    const headlineEl = document.getElementById('headlineText');
    const moveHandle = document.getElementById('moveHandle');
    const resizeHandle = document.getElementById('resizeHandle');
    const toolbar = document.getElementById('editorToolbar');

    let dragState = { dragging:false, offsetX:0, offsetY:0 };
    let resizeState = { resizing:false, startX:0, startY:0, startFont:30, startWidth:0 };
    let rafPending = false, lastX = 0, lastY = 0;

    const clamp = (v,min,max)=>Math.max(min,Math.min(max,v));
    const px = (n)=>Math.round(n)+'px';

    function normalizeHeadlinePosition(){
      const st = getComputedStyle(headlineEl);
      if (st.transform !== 'none' || st.left.endsWith('%')) {
        const cardRect = card.getBoundingClientRect();
        const rect = headlineEl.getBoundingClientRect();
        headlineEl.style.left = px(rect.left - cardRect.left);
        headlineEl.style.top  = px(rect.top  - cardRect.top);
        headlineEl.style.transform = 'none';
      }
    }

    function updateEditorUI(){
      const cardRect = card.getBoundingClientRect();
      const rect = headlineEl.getBoundingClientRect();
      moveHandle.style.left = px(rect.left - cardRect.left - 10);
      moveHandle.style.top  = px(rect.top  - cardRect.top  - 18);
      resizeHandle.style.left = px(rect.right - cardRect.left - 7);
      resizeHandle.style.top  = px(rect.bottom - cardRect.top - 7);

      const centerX = rect.left + rect.width/2 - cardRect.left;
      toolbar.style.left = px(centerX - toolbar.offsetWidth/2 || centerX);
      toolbar.style.top  = px((rect.top - cardRect.top) - 44);

      if (document.activeElement === headlineEl || headlineHovering) toolbar.style.display = 'flex';
    }

    let headlineHovering=false;
    headlineEl.addEventListener('mouseenter',()=>{headlineHovering=true;toolbar.style.display='flex';updateEditorUI();});
    headlineEl.addEventListener('mouseleave',()=>{headlineHovering=false;if(document.activeElement!==headlineEl)toolbar.style.display='none';});
    headlineEl.addEventListener('focus',()=>{toolbar.style.display='flex';updateEditorUI();});
    headlineEl.addEventListener('blur',()=>{if(!headlineHovering)toolbar.style.display='none';});
    window.addEventListener('resize',updateEditorUI);

    /* === মুভ === */
    moveHandle.addEventListener('mousedown',(e)=>{
      e.preventDefault();
      normalizeHeadlinePosition();
      const rect = headlineEl.getBoundingClientRect();
      const cardRect = card.getBoundingClientRect();
      dragState.dragging=true;
      dragState.offsetX = e.clientX - (rect.left - cardRect.left);
      dragState.offsetY = e.clientY - (rect.top  - cardRect.top);
      document.body.style.userSelect='none';
    });

    /* === রিসাইজ: X ⇒ width (line breaks), Y ⇒ font-size === */
    resizeHandle.addEventListener('mousedown',(e)=>{
      e.preventDefault();
      normalizeHeadlinePosition(); // পজিশনকে px-এ আনুন
      // width-ও px-এ ফিক্স করুন যাতে স্মুথ হয়
      const rect = headlineEl.getBoundingClientRect();
      headlineEl.style.width = px(rect.width);

      resizeState.resizing=true;
      resizeState.startX=e.clientX;
      resizeState.startY=e.clientY;
      resizeState.startFont=parseFloat(getComputedStyle(headlineEl).fontSize)||30;
      resizeState.startWidth=rect.width;
      document.body.style.userSelect='none';
    });

    // স্মুথ আপডেট: প্রতি ফ্রেমে একবার DOM-write
    document.addEventListener('mousemove',(e)=>{
      lastX = e.clientX; lastY = e.clientY;
      if (!rafPending && (dragState.dragging || resizeState.resizing)) {
        rafPending = true;
        requestAnimationFrame(applyFrame);
      }
    });

    function applyFrame(){
      rafPending = false;

      if (dragState.dragging) {
        const maxLeft = card.clientWidth - headlineEl.offsetWidth;
        const maxTop  = card.clientHeight - headlineEl.offsetHeight;
        let newLeft = lastX - dragState.offsetX;
        let newTop  = lastY - dragState.offsetY;
        newLeft = clamp(newLeft, 0, Math.max(0,maxLeft));
        newTop  = clamp(newTop, 0, Math.max(0,maxTop));
        headlineEl.style.left = px(newLeft);
        headlineEl.style.top  = px(newTop);
      }

      if (resizeState.resizing) {
        // Y: font-size (সেন্সিটিভিটি 0.5)
        const deltaY = lastY - resizeState.startY;
        let newFont = resizeState.startFont + deltaY * 0.5;
        newFont = clamp(newFont, 10, 150);
        headlineEl.style.fontSize = newFont + 'px';
        document.getElementById('headlineFontSize').value = Math.round(newFont);

        // X: width → line break
        const deltaX = lastX - resizeState.startX;
        const leftPx = parseFloat(headlineEl.style.left)||0;
        const paddingSafe = 20; // ডান দিকে সামান্য মার্জিন
        const maxW = card.clientWidth - leftPx - paddingSafe;
        let newW = resizeState.startWidth + deltaX; // ডানে টানলে চওড়া, বামে টানলে সরু
        newW = clamp(newW, 220, Math.max(220, maxW));
        headlineEl.style.width = px(newW);
      }

      if (dragState.dragging || resizeState.resizing) updateEditorUI();
    }

    document.addEventListener('mouseup',()=>{
      dragState.dragging=false;
      resizeState.resizing=false;
      document.body.style.userSelect='';
    });

    // টুলবার বাটন
    toolbar.addEventListener('click',(e)=>{
      const btn=e.target.closest('button'); if(!btn) return;
      const cmd=btn.getAttribute('data-cmd');
      if(cmd){ headlineEl.focus(); try{ document.execCommand(cmd,false,null);}catch(_){} return; }
      const align=btn.getAttribute('data-align');
      if(align){ headlineEl.style.textAlign=(align==='left'?'left':align==='right'?'right':'center'); updateEditorUI(); }
    });

    // ডাবল-ক্লিকে width রিসেট (ইচ্ছা করলে)
    resizeHandle.addEventListener('dblclick',()=>{
      headlineEl.style.width='90%'; // ডিফল্টে ফিরুন
      // আবার সেন্টার করতে ট্রান্সফর্ম সেট করুন
      headlineEl.style.left='50%';
      headlineEl.style.transform='translateX(-50%)';
      updateEditorUI();
    });

    // প্রথম লোড
    window.addEventListener('load', ()=>{
      updateEditorUI();
      document.getElementById('headlineInput').value = headlineEl.innerText;
      const selected = document.querySelector('input[name="bgSelect"]:checked')?.value || 'bg1';
      setBackground(selected);
    });
  </script>

  <script>
  // URL params সাপোর্ট (অপশনাল)
  (function(){
    const p=new URLSearchParams(location.search);
    const title=p.get('title');
    const img=p.get('img');
    const site=p.get('url')||location.hostname;
    const font=p.get('font')||'30';
    const dateParam=p.get('date');
    const logo=p.get('logo');
    const colorParam=p.get('color');

    if(title){ headlineText.innerText=title; headlineInput.value=title; }
    if(img){ mainImage.src=img; }
    if(site){ urlInput.value=site; urlText.innerText=site; }

    headlineFontSize.value=font; headlineText.style.fontSize=font+'px';

    if(colorParam){ headlineColor.value=colorParam; headlineText.style.color=colorParam; }
    else{ headlineText.style.color=headlineColor.value||'#000'; }

    const today=new Date();
    const defaultDate=today.toLocaleDateString('bn-BD',{day:'numeric',month:'long',year:'numeric'});
    const finalDate=(dateParam&&dateParam.trim()!=='')?dateParam:defaultDate;
    dateInput.value=finalDate; dateText.innerText=finalDate;

    if(logo){ logoImage.src=logo; }

    const bgParam=p.get('bg');
    if(bgParam && ['bg1','bg2','bg3'].includes(bgParam)){
      const r=document.querySelector(`input[name="bgSelect"][value="${bgParam}"]`);
      if(r){ r.checked=true; setBackground(bgParam); }
    }

    setTimeout(()=>{ headlineInput.dispatchEvent(new Event('input')); },0);
  })();
  </script>

</body>
</html>
