<?= $this->extend('layout/templatetool');?>
<?= $this->section('css') ?>
    <style>
        * { box-sizing: border-box; }
        body { font-family: 'Inter', sans-serif; background: #f8fafc; color: #334155; }
        .ctrl-select, .ctrl-file { 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-select:focus, .ctrl-file:focus { border-color:#0099b8; }
        
        .btn-dl { 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:#15803d; display:flex; align-items:center; justify-content:center; gap:8px; text-decoration:none; transition:background .12s; }
        .btn-dl:hover { background:#166534; }
        
        .btn-clear { width:100%; padding:10px; border-radius:10px; border:1px solid #e2e8f0; font-size:12px; font-weight:700; font-family:'Inter',sans-serif; color:#475569; background:#fff; cursor:pointer; transition:all .12s; }
        .btn-clear:hover { background:#fef2f2; color:#b91c1c; border-color:#fecaca; }

        .card { background:#fff; border:1px solid #e2e8f0; border-radius:20px; padding:28px; box-shadow:0 2px 12px rgba(0,0,0,.04); }

        /* Color Picker Buttons */
        .color-options { display: flex; gap: 10px; align-items: center; }
        .color-btn { width: 32px; height: 32px; border-radius: 50%; border: 2px solid #e2e8f0; cursor: pointer; transition: transform 0.12s, border-color 0.12s; }
        .color-btn.active { border-color: #0099b8; transform: scale(1.15); box-shadow: 0 0 0 3px rgba(0, 153, 184, 0.2); }

        /* Container Preview Canvas TTD */
        #sigContainer { 
            display: flex; 
            justify-content: center; 
            align-items: center; 
            width: 100%; 
            height: 260px; 
            background: #ffffff; 
            border: 2px dashed #cbd5e1; 
            border-radius: 16px; 
            overflow: hidden;
            touch-action: none;
            position: relative;
        }
        #sigCanvas { 
            width: 100%; 
            height: 100%; 
            cursor: crosshair; 
        }
    </style>
<?= $this->endSection(); ?>

<?= $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> › Tanda Tangan Dan Stempel Digital
        </p>
        <h1 class="text-2xl font-bold mb-1">✍️ Tanda Tangan Dan Stempel Digital </h1>
        <p class="text-sm text-purple-100">Buat TTD manual atau ekstrak foto TTD & Stempel dari kertas, ubah warna tinta, lalu unduh PNG transparan.</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">✍️ Tanda Tangan Dan Stempel Digital</span>
    </div>

    <div style="display:grid;grid-template-columns:1fr 1fr;gap:20px" class="items-start">

        <!-- PANEL KONTROL -->
        <div class="card space-y-4">
            <!-- UPLOAD FOTO TTD -->
            <div>
                <label style="font-size:12px;font-weight:700;color:#475569;display:block;margin-bottom:6px">📷 Upload Foto TTD (Dari Kertas)</label>
                <input type="file" id="uploadInput" class="ctrl-file" accept="image/*" onchange="handleImageUpload(this)">
                <div style="font-size:10px;color:#94a3b8;margin-top:4px">
                    *Background putih dihilangkan otomatis & warna tinta dapat disesuaikan.
                </div>
            </div>

            <hr style="border:0;border-top:1px solid #e2e8f0;margin:12px 0;">

            <!-- PILIH WARNA TINTA -->
            <div>
                <label style="font-size:12px;font-weight:700;color:#475569;display:block;margin-bottom:8px">Warna Tinta</label>
                <div class="color-options">
                    <button type="button" class="color-btn active" style="background: #000000;" onclick="changeInkColor('#000000', this)"></button>
                    <button type="button" class="color-btn" style="background: #1e40af;" onclick="changeInkColor('#1e40af', this)"></button>
                    <button type="button" class="color-btn" style="background: #991b1b;" onclick="changeInkColor('#991b1b', this)"></button>
                </div>
            </div>

            <!-- KETEBALAN GARIS -->
            <div>
                <label style="font-size:12px;font-weight:700;color:#475569;display:block;margin-bottom:6px">Ketebalan Garis (Gambar Manual)</label>
                <select id="penWidth" class="ctrl-select" onchange="setPenWidth(this.value)">
                    <option value="2">Tipis (2px)</option>
                    <option value="3" selected>Sedang (3px)</option>
                    <option value="5">Tebal (5px)</option>
                </select>
            </div>

            <!-- TOMBOL HAPUS -->
            <button type="button" class="btn-clear" onclick="clearCanvas()">
                🗑️ Hapus & Ulangi
            </button>
        </div>

        <!-- PREVIEW & DOWNLOAD -->
        <div class="card space-y-4">
            <div style="font-size:12px;font-weight:700;color:#475569">Area Tanda Tangan</div>
            
            <div id="sigContainer">
                <canvas id="sigCanvas"></canvas>
            </div>

            <button type="button" class="btn-dl" onclick="downloadSignature()">
                💾 Download PNG Transparan
            </button>

            <div style="font-size:10px;color:#94a3b8;text-align:center;line-height:1.6">
                💡 Gambar berformat PNG transparan dapat langsung ditempel ke dokumen Word, PDF, atau aplikasi lain.
            </div>
        </div>

    </div>
</main>
<?= $this->endSection(); ?>

<?= $this->section('myscript') ?>
<script>
    let canvas, ctx;
    let isDrawing = false;
    let inkColor = '#000000';
    let penWidth = 3;
    let hasSignature = false;
    let originalUploadedImg = null; 

    window.addEventListener('DOMContentLoaded', () => {
        canvas = document.getElementById('sigCanvas');
        ctx = canvas.getContext('2d');

        resizeCanvas();
        window.addEventListener('resize', resizeCanvas);

        // Event Mouse
        canvas.addEventListener('mousedown', startDrawing);
        canvas.addEventListener('mousemove', draw);
        canvas.addEventListener('mouseup', stopDrawing);
        canvas.addEventListener('mouseleave', stopDrawing);

        // Event Touch (HP / Tablet)
        canvas.addEventListener('touchstart', handleTouchStart, { passive: false });
        canvas.addEventListener('touchmove', handleTouchMove, { passive: false });
        canvas.addEventListener('touchend', stopDrawing);
    });

    function resizeCanvas() {
        const container = document.getElementById('sigContainer');
        
        const tempCanvas = document.createElement('canvas');
        const tempCtx = tempCanvas.getContext('2d');
        tempCanvas.width = canvas.width;
        tempCanvas.height = canvas.height;
        if (hasSignature) tempCtx.drawImage(canvas, 0, 0);

        canvas.width = container.clientWidth;
        canvas.height = container.clientHeight;

        ctx.strokeStyle = inkColor;
        ctx.lineWidth = penWidth;
        ctx.lineCap = 'round';
        ctx.lineJoin = 'round';

        if (hasSignature && !originalUploadedImg) {
            ctx.drawImage(tempCanvas, 0, 0);
        } else if (originalUploadedImg) {
            renderUploadedImage();
        }
    }

    function changeInkColor(color, element) {
        inkColor = color;
        ctx.strokeStyle = color;

        document.querySelectorAll('.color-btn').forEach(btn => btn.classList.remove('active'));
        if (element) element.classList.add('active');

        if (originalUploadedImg) {
            renderUploadedImage();
        }
    }

    function setPenWidth(width) {
        penWidth = parseInt(width);
        ctx.lineWidth = penWidth;
    }

    function getPos(e) {
        const rect = canvas.getBoundingClientRect();
        return {
            x: e.clientX - rect.left,
            y: e.clientY - rect.top
        };
    }

    function startDrawing(e) {
        if (originalUploadedImg) {
            originalUploadedImg = null;
            document.getElementById('uploadInput').value = '';
        }
        isDrawing = true;
        hasSignature = true;
        const pos = getPos(e);
        ctx.beginPath();
        ctx.moveTo(pos.x, pos.y);
    }

    function draw(e) {
        if (!isDrawing) return;
        const pos = getPos(e);
        ctx.lineTo(pos.x, pos.y);
        ctx.stroke();
    }

    function stopDrawing() {
        isDrawing = false;
        ctx.beginPath();
    }

    function handleTouchStart(e) {
        e.preventDefault();
        if (e.touches.length === 1) {
            startDrawing(e.touches[0]);
        }
    }

    function handleTouchMove(e) {
        e.preventDefault();
        if (e.touches.length === 1) {
            draw(e.touches[0]);
        }
    }

    function clearCanvas() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        document.getElementById('uploadInput').value = '';
        originalUploadedImg = null;
        hasSignature = false;
    }

    function handleImageUpload(input) {
        const file = input.files[0];
        if (!file) return;

        const reader = new FileReader();
        reader.onload = function(e) {
            const img = new Image();
            img.onload = function() {
                originalUploadedImg = img;
                renderUploadedImage();
            };
            img.src = e.target.result;
        };
        reader.readAsDataURL(file);
    }

    function renderUploadedImage() {
        if (!originalUploadedImg) return;

        ctx.clearRect(0, 0, canvas.width, canvas.height);

        const img = originalUploadedImg;
        const offscreenCanvas = document.createElement('canvas');
        const offCtx = offscreenCanvas.getContext('2d');
        offscreenCanvas.width = img.width;
        offscreenCanvas.height = img.height;

        offCtx.drawImage(img, 0, 0);
        const imgData = offCtx.getImageData(0, 0, img.width, img.height);
        const data = imgData.data;

        const targetRGB = hexToRgb(inkColor);

        for (let i = 0; i < data.length; i += 4) {
            const r = data[i];
            const g = data[i + 1];
            const b = data[i + 2];

            // Hapus latar putih/terang
            if (r > 180 && g > 180 && b > 180) {
                data[i + 3] = 0;
            } else {
                // Ubah warna coretan sesuai warna tinta aktif
                data[i] = targetRGB.r;
                data[i + 1] = targetRGB.g;
                data[i + 2] = targetRGB.b;
            }
        }

        offCtx.putImageData(imgData, 0, 0);

        const scale = Math.min((canvas.width - 20) / img.width, (canvas.height - 20) / img.height);
        const x = (canvas.width - img.width * scale) / 2;
        const y = (canvas.height - img.height * scale) / 2;

        ctx.drawImage(offscreenCanvas, x, y, img.width * scale, img.height * scale);
        hasSignature = true;
    }

    function hexToRgb(hex) {
        const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
        return result ? {
            r: parseInt(result[1], 16),
            g: parseInt(result[2], 16),
            b: parseInt(result[3], 16)
        } : { r: 0, g: 0, b: 0 };
    }

    function downloadSignature() {
        if (!hasSignature) {
            alert('Silakan buat tanda tangan atau upload foto TTD terlebih dahulu.');
            return;
        }

        const link = document.createElement('a');
        link.download = 'tanda-tangan-digital.png';
        link.href = canvas.toDataURL('image/png');
        link.click();
    }
</script>
<?= $this->endSection(); ?>