<?= $this->extend('layout/templatetool');?>

<!-- Untuk Css -->
<?= $this->section('css') ?>
	 <style>
        * { box-sizing: border-box; }
        body { font-family: 'Inter', sans-serif; background: #f8fafc; color: #334155; }
        .nav-active { background:#0099b8; color:#fff !important; border-radius:6px; }
        .upload-zone { border:2px dashed #cbd5e1; border-radius:14px; padding:36px 20px; text-align:center; cursor:pointer; transition:all .15s; background:#f8fafc; }
        .upload-zone:hover,.upload-zone.drag { border-color:#0099b8; background:#e0f7ff; }
        .upload-zone input { display:none; }
        .ctrl-input,.ctrl-select { padding:8px 12px; border-radius:10px; border:1px solid #e2e8f0; font-size:13px; font-family:'Inter',sans-serif; outline:none; color:#1e293b; background:#fff; width:100%; }
        .ctrl-input:focus,.ctrl-select:focus { border-color:#0099b8; box-shadow:0 0 0 3px rgba(0,153,184,.1); }
        .btn-go { width:100%; padding:13px; border-radius:12px; border:none; font-size:13px; font-weight:700; cursor:pointer; font-family:'Inter',sans-serif; color:#fff; background:#0099b8; transition:background .12s; display:flex; align-items:center; justify-content:center; gap:8px; }
        .btn-go:hover { background:#007fa0; }
        .btn-go:disabled { background:#94a3b8; cursor:not-allowed; }
        .btn-dl { width:100%; padding:12px; border-radius:12px; border:none; font-size:13px; font-weight:700; cursor:pointer; font-family:'Inter',sans-serif; color:#fff; background:#15803d; display:flex; align-items:center; justify-content:center; gap:8px; text-decoration:none; transition:background .12s; margin-top:8px; }
        .btn-dl:hover { background:#166534; }
        .result-ok  { background:#f0fdf4; border:1px solid #bbf7d0; border-radius:10px; padding:12px 16px; font-size:12px; color:#166534; font-weight:600; }
        .result-err { background:#fef2f2; border:1px solid #fecaca; border-radius:10px; padding:12px 16px; font-size:12px; color:#b91c1c; }
        .preview-box { border-radius:12px; overflow:hidden; background:#f1f5f9; border:1px solid #e2e8f0; text-align:center; }
        .preview-box img { max-width:100%; max-height:220px; object-fit:contain; display:block; margin:auto; }
        .card { background:#fff; border:1px solid #e2e8f0; border-radius:20px; padding:28px; box-shadow:0 2px 12px rgba(0,0,0,.04); }
        .fmt-btn { padding:10px 18px; border-radius:12px; border:2px solid #e2e8f0; font-size:13px; font-weight:700; cursor:pointer; transition:all .12s; background:#fff; font-family:'Inter',sans-serif; color:#475569; }
        .fmt-btn.sel { background:#0099b8; color:#fff; border-color:#0099b8; }
        .fmt-btn:not(.sel):hover { background:#f1f5f9; border-color:#cbd5e1; }
        .range-wrap { display:flex; align-items:center; gap:10px; }
        .range-wrap input[type=range] { flex:1; accent-color:#0099b8; }
        .range-val { font-size:14px; font-weight:700; color:#0099b8; min-width:44px; text-align:right; }
    </style>
<?= $this->endSection(); ?>


<!-- Untuk Main -->
<?= $this->section('conten');?>
	<section style="background:linear-gradient(135deg,#1e1b4b 0%,#4c1d95 50%,#0099b8 100%)">
    <div class="max-w-3xl mx-auto px-6 py-10 text-white">
        <p class="text-xs text-purple-200 uppercase tracking-widest font-medium mb-1">
            <a href="<?= base_url('tools')?>" class="hover:underline">Alat Digital</a> › Konversi Format
        </p>
        <h1 class="text-2xl font-bold mb-1">🔄 Multi-Format Image Converter</h1>
        <p class="text-sm text-purple-100">Konversi gambar ke JPG, PNG, WEBP, AVIF, SVG, BMP, & ICO — seratus persen diproses lokal di browser Anda.</p>
    </div>
</section>

<main class="max-w-3xl mx-auto px-4 py-8 space-y-5">

    <div class="bg-white border border-slate-200 rounded-xl px-4 py-3 flex items-center gap-3 shadow-sm flex-wrap">
        <a href="<?= base_url('tools')?>" class="bg-slate-50 hover:bg-slate-100 border border-slate-200 text-slate-700 text-[11px] font-bold py-1 px-3 rounded-lg transition">⬅ Kembali ke Alat Digital</a>
        <div class="h-4 w-px bg-slate-200"></div>
        <span class="text-xs font-bold text-slate-700">🔄 Konversi Format Gambar</span>
    </div>

    <div class="card space-y-6">
        <div class="upload-zone" onclick="document.getElementById('cvInput').click()"
            ondragover="event.preventDefault();this.classList.add('drag')"
            ondragleave="this.classList.remove('drag')"
            ondrop="dropFile(event,'cvInput',previewConvert)">
            <input type="file" id="cvInput" accept="image/*" onchange="previewConvert(this)">
            <div style="font-size:40px;margin-bottom:8px">🔄</div>
            <div style="font-size:13px;font-weight:600;color:#475569"><b style="color:#0099b8">Klik untuk pilih gambar</b> atau seret ke sini</div>
            <div style="font-size:11px;color:#94a3b8;margin-top:4px">JPG · PNG · WEBP · SVG · AVIF · GIF · BMP</div>
        </div>

        <div id="cvPreview" style="display:none" class="preview-box">
            <img id="cvPreviewImg" alt="preview">
            <div style="font-size:11px;color:#64748b;padding:8px 12px;font-weight:500" id="cvOrigInfo"></div>
        </div>

        <!-- FORMAT SELECTOR -->
        <div>
            <div style="font-size:12px;font-weight:700;color:#475569;margin-bottom:10px">Konversi ke format:</div>
            <div style="display:flex;gap:8px;flex-wrap:wrap">
                <button class="fmt-btn sel" id="cvJpg"  onclick="selectFmt('jpeg')">JPEG</button>
                <button class="fmt-btn"     id="cvPng"  onclick="selectFmt('png')">PNG</button>
                <button class="fmt-btn"     id="cvWebp" onclick="selectFmt('webp')">WEBP</button>
                <button class="fmt-btn"     id="cvAvif" onclick="selectFmt('avif')">AVIF</button>
                <button class="fmt-btn"     id="cvSvg"  onclick="selectFmt('svg')">SVG</button>
                <button class="fmt-btn"     id="cvBmp"  onclick="selectFmt('bmp')">BMP</button>
                <button class="fmt-btn"     id="cvIco"  onclick="selectFmt('ico')">ICO</button>
            </div>
            <div id="cvFmtDesc" style="font-size:11px;color:#64748b;margin-top:8px;padding:8px 12px;background:#f8fafc;border-radius:8px">
                📌 <b>JPEG</b> — Format paling umum, ukuran kecil, cocok untuk foto. Tidak mendukung transparansi.
            </div>
        </div>

        <!-- QUALITY -->
        <div id="cvQualRow">
            <label style="font-size:12px;font-weight:700;color:#475569;display:block;margin-bottom:8px">Kualitas Output</label>
            <div class="range-wrap">
                <input type="range" id="cvQual" min="10" max="95" value="85"
                    oninput="document.getElementById('cvQualVal').innerText=this.value+'%'">
                <span class="range-val" id="cvQualVal">85%</span>
            </div>
        </div>

        <button class="btn-go" id="cvBtn" onclick="doConvert()" disabled>
            <i class="fa-solid fa-arrows-rotate fa-xs"></i> Konversi Sekarang
        </button>

        <div id="cvResult" style="display:none"></div>
    </div>

    <div class="bg-blue-50 border border-blue-200 rounded-xl p-4 text-xs text-blue-800 leading-relaxed space-y-1">
        <strong>💡 Ringkasan Karakteristik Format:</strong><br>
        • <b>JPEG</b> — Kompresi tinggi, cocok untuk fotografi.<br>
        • <b>PNG</b> — Lossless & mendukung latar belakang transparan.<br>
        • <b>WEBP / AVIF</b> — Generasi baru dengan kompresi sangat efisien untuk website.<br>
        • <b>SVG</b> — Format vektor (membungkus citra untuk kebutuhan embed web/desain).<br>
        • <b>BMP & ICO</b> — Format standar Windows / Favicon website.
    </div>
</main>
<?= $this->endSection(); ?>


<!-- Untuk Js -->

<?= $this->section('myscript') ?>
	<script>
function fmtSize(b) {
    if(b<1024) return b+' B';
    if(b<1048576) return (b/1024).toFixed(1)+' KB';
    return (b/1048576).toFixed(2)+' MB';
}

function dropFile(e,id,cb) {
    e.preventDefault(); e.currentTarget.classList.remove('drag');
    const f=e.dataTransfer.files[0]; if(!f) return;
    const dt=new DataTransfer(); dt.items.add(f);
    const inp=document.getElementById(id); inp.files=dt.files; cb(inp);
}

function readURL(file) { return new Promise(r=>{ const fr=new FileReader(); fr.onload=e=>r(e.target.result); fr.readAsDataURL(file); }); }
function loadImg(src)  { return new Promise((r,j)=>{ const i=new Image(); i.onload=()=>r(i); i.onerror=j; i.src=src; }); }

const fmtDescs = {
    jpeg:'📌 <b>JPEG</b> — Format standar universal, ukuran ringkas, ideal untuk foto.',
    png:'📌 <b>PNG</b> — Mempertahankan transparansi dan kualitas tanpa kehilangan detail (lossless).',
    webp:'📌 <b>WEBP</b> — Format modern web dari Google dengan rasio kompresi sangat tinggi.',
    avif:'📌 <b>AVIF</b> — Format generasi terbaru dengan kualitas visual tinggi pada ukuran file yang minim.',
    svg:'📌 <b>SVG</b> — Format Vektor XML. Pembungkusan terstruktur agar dapat digunakan di aplikasi vektor/web.',
    bmp:'📌 <b>BMP</b> — Bitmap tanpa kompresi standar Windows dengan detail piksel murni.',
    ico:'📌 <b>ICO</b> — Format ikon standar untuk favicon situs web dan aplikasi desktop.'
};

let cvFile=null, cvFmt='jpeg';

function selectFmt(f) {
    cvFmt=f;
    ['cvJpg','cvPng','cvWebp','cvAvif','cvSvg','cvBmp','cvIco'].forEach(id=>{
        const el = document.getElementById(id);
        if(el) el.classList.remove('sel');
    });
    
    const map={jpeg:'cvJpg',png:'cvPng',webp:'cvWebp',avif:'cvAvif',svg:'cvSvg',bmp:'cvBmp',ico:'cvIco'};
    if(map[f]) document.getElementById(map[f]).classList.add('sel');
    
    // Tampilkan pengatur kualitas hanya untuk format ber-kompresi lossy
    const supportsQuality = ['jpeg','webp','avif'].includes(f);
    document.getElementById('cvQualRow').style.display = supportsQuality ? 'block' : 'none';
    document.getElementById('cvFmtDesc').innerHTML = fmtDescs[f] || '';
}

async function previewConvert(inp) {
    cvFile=inp.files[0]; if(!cvFile) return;
    const url=await readURL(cvFile);
    document.getElementById('cvPreviewImg').src=url;
    document.getElementById('cvPreview').style.display='block';
    document.getElementById('cvOrigInfo').innerText=`${cvFile.name} · ${fmtSize(cvFile.size)}`;
    document.getElementById('cvBtn').disabled=false;
    document.getElementById('cvResult').style.display='none';
}

async function doConvert() {
    if(!cvFile) return;
    const qual = parseInt(document.getElementById('cvQual').value)/100;
    const btn = document.getElementById('cvBtn');
    btn.disabled = true; 
    btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Mengkonversi...';

    try {
        const url = await readURL(cvFile);
        const img = await loadImg(url);
        
        let blob = null;
        let ext = cvFmt === 'jpeg' ? 'jpg' : cvFmt;

        // 1. Penanganan Khusus Format SVG
        if (cvFmt === 'svg') {
            const svgContent = `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="${img.naturalWidth}" height="${img.naturalHeight}" viewBox="0 0 ${img.naturalWidth} ${img.naturalHeight}">
  <image width="${img.naturalWidth}" height="${img.naturalHeight}" xlink:href="${url}"/>
</svg>`;
            blob = new Blob([svgContent], { type: 'image/svg+xml;charset=utf-8' });
        } 
        // 2. Penanganan Format berbasis Canvas (JPEG, PNG, WEBP, AVIF, BMP, ICO)
        else {
            const canvas = document.createElement('canvas');
            
            // Khusus ikon (.ico), sesuaikan ke dimensi standar favicon jika terlalu besar
            if(cvFmt === 'ico') {
                const size = Math.min(img.naturalWidth, img.naturalHeight, 256);
                canvas.width = size;
                canvas.height = size;
            } else {
                canvas.width = img.naturalWidth;
                canvas.height = img.naturalHeight;
            }

            const ctx = canvas.getContext('2d');
            
            // Format tanpa transparansi diisi latar belakang putih
            if(['jpeg','bmp'].includes(cvFmt)) { 
                ctx.fillStyle = '#ffffff'; 
                ctx.fillRect(0, 0, canvas.width, canvas.height); 
            }
            
            ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

            // Ekstraksi Blob
            const mimeType = cvFmt === 'ico' ? 'image/x-icon' : (cvFmt === 'bmp' ? 'image/bmp' : 'image/' + cvFmt);
            
            blob = await new Promise(resolve => {
                canvas.toBlob(b => {
                    // Fallback jika browser belum mendukung ekspor native BMP/ICO/AVIF melalui canvas.toBlob
                    if (!b) {
                        canvas.toBlob(fallbackBlob => resolve(fallbackBlob), 'image/png');
                    } else {
                        resolve(b);
                    }
                }, mimeType, ['jpeg','webp','avif'].includes(cvFmt) ? qual : undefined);
            });
        }

        const dlUrl = URL.createObjectURL(blob);
        const fname = cvFile.name.replace(/\.[^.]+$/, '') + '.' + ext;
        const res = document.getElementById('cvResult');
        
        res.style.display = 'block';
        res.innerHTML = `
            <div class="result-ok">✅ Berhasil dikonversi ke <b>${cvFmt.toUpperCase()}</b> · ${fmtSize(blob.size)}</div>
            <a href="${dlUrl}" download="${fname}" class="btn-dl">
                <i class="fa-solid fa-download fa-xs"></i> Unduh ${cvFmt.toUpperCase()} (${fmtSize(blob.size)})
            </a>`;

    } catch (err) {
        console.error(err);
        const res = document.getElementById('cvResult');
        res.style.display = 'block';
        res.innerHTML = `<div class="result-err">❌ Gagal mengkonversi gambar. Pastikan file tidak rusak.</div>`;
    } finally {
        btn.disabled = false; 
        btn.innerHTML = '<i class="fa-solid fa-arrows-rotate fa-xs"></i> Konversi Lagi';
    }
}
</script>
<?= $this->endSection(); ?>